drake900918 2015-07-21 07:18
浏览 874
已采纳

GO Websocket向所有客户发送消息

Everything works fine with this code (shortened it for better reading).

When Client1 sends a request to the Server, the Server responses to him instantly. But, the other clients can not see the response message.

So I want to make it go further: When a client sends a request to the server, the server will response to all clients so that all clients can see the message.

How can I do that? Any examples or nice tutorials for beginners?

Thanks in advance!

Server:

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
      }
    }
}
  • 写回答

1条回答 默认 最新

  • dongyao5843 2015-07-21 07:22
    关注

    You have to use connection pool to broadcast messages to all connections. You can use that as tutorial/sample http://gary.burd.info/go-websocket-chat

    Simplifying:
    Connection pool is a collection of registered connections. See 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
    
        ...
    }
    

    To broadcast message for all clients, we iterate over connection pool like this:

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

    h.broadcast in that example is a channel with messages we need to broadcast.
    We use default section of the select statement to delete connections with full or blocked send channels. See What is the benefit of sending to a channel by using select in Go?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换