2 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
golang.org/x/net/websocket 沒有實(shí)現(xiàn) RFC 6455 中的 ping-pong,但是 gorilla websocket實(shí)現(xiàn)了。Gorilla websocket 的最小示例
c := time.Tick(pingInterval)
go func(){
for _ := range c {
if err := conn.WriteControl(Ping...); err != nil {
handle error
}
}
}()
-----
conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(pingInterval)) })
go func(){
for {
if _, _, err := conn.NextReader(); err != nil {
handle error
}
}
}()

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
我誤讀了你原來的問題。
不,你馬上就做。您基本上需要阻止處理程序返回以保持 websocket 連接活動(dòng)。如果您不關(guān)心該消息,只需將其丟棄并且不對(duì)其進(jìn)行任何處理。
一種常見的方式人們做的是有一個(gè)專門的Read和Write夠程,是這樣的:
func fishHandler(ws *websocket.Conn) {
id := ws.RemoteAddr().String() + "-" + ws.Request().RemoteAddr + "-" + ws.Request().UserAgent()
sockets[id] = ws
go writePump(ws)
readPump(ws)
}
func readPump(ws *websocket.Conn) {
defer ws.Close()
msg := make([]byte, 512)
_, err := ws.Read(msg)
if err != nil {
return
}
}
func writePump(ws *websocket.Conn) {
// Hand the write messages here
}
- 2 回答
- 0 關(guān)注
- 257 瀏覽
添加回答
舉報(bào)