WebsocketServer:将事件消息发送到连接的客户端

时间:2019-07-08 19:16:08

标签: go websocket

问题很简单:我有WS服务器,它是“ for {}”的。我需要“注册”连接的用户,然后在事件(CoreWS函数外部)上发送消息。我添加了NodeJS示例,它可以完全满足我的需要,以更好地理解。

失败的Go语言代码: 我正在使用此pkg https://github.com/gobwas/ws

var conn_itf interface{} //yeah,
var op_itf interface{} //i know it's not how it works

func main() {
    go collector()
    go sender()
    http.ListenAndServe(":3333", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        conn, _, _, err := ws.UpgradeHTTP(r, w)
        if err != nil {
            // handle error
        }
        go func() {
            defer conn.Close()

            for {
                msg, op, err := wsutil.ReadClientData(conn)
                conn_itf = conn // i'm trying to "register" user
                op_itf = op
                if err != nil {

                }
                err = wsutil.WriteServerMessage(conn, op, msg)
                if err != nil {

                }
            }
        }()
    }))
}

func collector() {
    for {
        fmt.Println("conn: ", conn_itf)
        fmt.Println("op: ", op_itf)
        time.Sleep(10000 * time.Millisecond)
    }
}

func sender() {
    for {
        msg := []byte("Hello world!")
        time.Sleep(50000 * time.Millisecond)
        wsutil.WriteServerMessage(conn_itf, op_itf, msg)  //invoking ws-send
    }
}

有效的NodeJS:

const wss = new WebSocket.Server({ port: 3333 })
wss.on('connection', ws => {
    sockets.set('key', ws) //this code remember active connection
    ws.on('message', message => {
      console.log(`Received message => ${message}`)
    })

})


function callsend(data) {
    const ws = sockets.get('key') //this code sending message on invoking
    ws.send(data)
}

0 个答案:

没有答案