【问题标题】:GO Websocket send all clients a messageGO Websocket 向所有客户端发送消息
【发布时间】:2015-07-21 07:18:55
【问题描述】:

这段代码一切正常(为了更好地阅读而缩短了它)。

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
      }
    }
}

【问题讨论】:

    标签: go websocket


    【解决方案1】:

    您必须使用连接池向所有连接广播消息。 您可以将其用作教程/示例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
    
        ...
    }
    

    为了向所有客户端广播消息,我们像这样遍历连接池:

        case m := <-h.broadcast:
            for c := range h.connections {
                select {
                case c.send <- m:
                default:
                    delete(h.connections, c)
                    close(c.send)
                }
            }
        }
    

    h.broadcast 在该示例中是一个包含我们需要广播的消息的频道。
    我们使用select 语句的default 部分来删除具有完整或阻塞发送通道的连接。见What is the benefit of sending to a channel by using select in Go?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 2019-04-29
    • 2021-07-18
    • 2019-06-14
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多