duanjiuhong5843 2018-05-24 05:12
浏览 2307
已采纳

如何从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 2018-05-25 05:49
    关注

    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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?