duanjiuhong5843
duanjiuhong5843
2018-05-24 05:12

如何从golang的websocket服务器向客户端主动发送消息

已采纳

I'm a newcomer for the golang and websocket.

I'm trying to write a websocket server which can send the messages actively to client once the handshake is done.

but my server will just only send the message to the client when got the request from the client.

Does anyone know how to implement this feature or where can I find the related answer for that?

Thank you so much.

the source code is as follows:

package main

import (
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte("Hi, the handshake is completed.
"))
    w.Write([]byte("Let's start to talk something.
"))
}

func main() {
    http.HandleFunc("/", handler)
    log.Printf("Start to listen on 443.")
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    log.Fatal(err)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douju1968 douju1968 3年前

    Try package websocket.

    Here's a simple example grab from the Godoc:

    var upgrader = websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Println(err)
            return
        }
        defer conn.Close()
    
        msg := []byte("Let's start to talk something.")
        err = conn.WriteMessage(websocket.TextMessage, msg)
        if err != nil {
            log.Println(err)
        }
    
        // do other stuff...
    }
    
    点赞 评论 复制链接分享
  • duan5362 duan5362 3年前

    Thanks you all for you both's help to answer me. and sorry for the very late reply here.

    You both's answer is really helpful and I learn a lot.

    Finally, I also find the simple way to achieve the same result without using the gorilla, here comes my code:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
        "golang.org/x/net/websocket"
    )
    
    func Echo(ws *websocket.Conn) {
        var err error
        msg := `Hi, the handshake it complete!`
    
        for {
            if err = websocket.Message.Send(ws, msg); err != nil {
                fmt.Println("Can't send")
            } else {
                fmt.Println("Sending")
            }
        }
    }
    
    func main() {
        http.Handle("/", websocket.Handler(Echo))
    
        if err := http.ListenAndServeTLS("10.10.10.10:1010", "server.crt", "server.key", nil); err != nil {
            log.Fatal("ListenAndServe:", err)
        }
    }
    
    点赞 评论 复制链接分享
  • dongwanqiang_2017 dongwanqiang_2017 3年前

    first of all, youre server is on http not websocket (for that you can upgrade it to websocket using gorilla e.g)

    second, before client making a request there is no way to response him because you have no connection with him (daaa)

    点赞 评论 复制链接分享

相关推荐