duanjiao6730 2010-08-25 13:27
浏览 128
已采纳

如何从Go WebSocket处理程序访问其他客户端连接?

Note: I'm more interested in understanding general Go concepts/patterns, rather than solving this contrived example.

The Go (golang) WebSocket package provides a trivial echo server example, which condenses down to something like this:

func EchoServer(ws *websocket.Conn) { io.Copy(ws, ws); }

func main() {
 http.Handle("/echo", websocket.Handler(EchoServer));
 http.ListenAndServe(":12345", nil);
}

The server handles simultaneous connections, and I'm trying to upgrade it to a basic chat server by echoing the input to all connected clients.

How would I go about providing the EchoServer handler access to each of the open connections?

  • 写回答

1条回答 默认 最新

  • doushi2047 2010-08-25 14:44
    关注

    A quick little almost-functional example to give you an idea

    var c = make(chan *websocket.Conn, 5) //5 is an arbitrary buffer size
    var c2 = make(chan []byte, 5)
    func EchoServer(ws *websocket.Conn) {
        buff := make([]byte, 256)
        c <- ws
        for size, e := ws.Read(buff); e == nil; size, e = ws.Read(buff) {
            c2 <- buff[0:size]
        }
        ws.Close()
    }
    func main() {
        go func() {
            var somekindofstorage
            for {
                select {
                case newC := <-c:
                    somekindofstorage.Add(newC)
                case msg := <-c2:
                    for _, v := range somekindofstorage {
                        if _, e := v.Write(msg); e != nil { //assuming the client disconnected on write errors
                            somekindofstorage.Remove(v)
                        }
                    }
                }
            }
        }()
        http.Handle("/echo", websocket.Handler(EchoServer));
        http.ListenAndServe(":12345", nil);
    }
    

    This starts a goroutine that listens on two channels, one for new connections to add and one for messages to send to all active connection. somekindofstorage could be a map or a vector.

    Edit:

    Alternatively, you could just store all connections in a global map and write to each from EchoServer. But maps aren't designed to be accessed concurrently.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?