使用此代码一切正常(缩短它以便更好地阅读).
当Client1向服务器发送请求时,服务器立即响应他.但是,其他客户端无法看到响应消息.
所以我想进一步说明:当客户端向服务器发送请求时,服务器将响应所有客户端,以便所有客户端都能看到该消息.
我怎样才能做到这一点?适合初学者的任何示例或精彩教程?
提前致谢!
服务器:
import (
"github.com/gorilla/websocket"
)
func main() {
http.Handle("/server", websocket.Handler(echoHandler))
}
func echoHandler(ws *websocket.Conn) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
return
}
print_binary(p) // simple print of the message
err = conn.WriteMessage(messageType, p);
if err != nil {
return
}
}
}
Run Code Online (Sandbox Code Playgroud)
您必须使用连接池将消息广播到所有连接.您可以将其用作教程/示例http://gary.burd.info/go-websocket-chat
简化:
连接池是已注册连接的集合.见hub.connections:
type connection struct {
// The websocket connection.
ws *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
// The hub.
h *hub
}
type hub struct {
// Registered connections. That's a connection pool
connections map[*connection]bool
...
}
Run Code Online (Sandbox Code Playgroud)
要为所有客户端广播消息,我们迭代连接池,如下所示:
case m := <-h.broadcast:
for c := range h.connections {
select {
case c.send <- m:
default:
delete(h.connections, c)
close(c.send)
}
}
}
Run Code Online (Sandbox Code Playgroud)
h.broadcast在该示例中是一个包含我们需要广播的消息的频道.
我们使用语句的default部分select删除完整或阻止发送通道的连接.请参阅使用Go中的select,发送到频道有什么好处?
| 归档时间: |
|
| 查看次数: |
6938 次 |
| 最近记录: |