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

Problem is simple: i have WS server that doing it's "for {}". I need "register" connected user, then send message on event(outside of CoreWS function). I'm added NodeJS example that doing exactly what i need, for better understanding.

Go Lang Code that fails: i'm using this 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 that working:

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)
}
doudou32012
doudou32012 我需要完全像NodeJS中的Example一样。使用变量来发送消息或发送频道可能会更容易,但是我的目标是学习。
大约一年之前 回复
dongshi8359
dongshi8359 存放它们是什么意思?在记忆中?套接字连接conn就在那儿供您在无穷的for循环中使用(应该突破错误)。您根本不需要自己碰任何读者。
大约一年之前 回复
duanfu5239
duanfu5239 大猩猩可能更流行,更常见,但是Io.Writer和OpConn可能遇到同样的问题。直接的问题是存储它们,我不知道该怎么做。
大约一年之前 回复
dr637349
dr637349 我个人更喜欢github.com/gorilla/websocket。我在游戏服务器中使用它:github.com/hewiefreeman/GopherGameServer
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐