golang 读取了大量的 websockets

在过去的几周里,我一直潜伏在 Stack Overflow 上寻找与阅读大量 websocket 相关的信息。基本上,我有许多主机都通过 websocket 发出消息,我需要聚合它们。


到目前为止,我已经使用 Golang 完成了单个 websocket 连接。我也使用 Python 完成了我正在寻找的东西,但我真的很想在 Go 中做到这一点!


我使用了 gorilla 的 websocket 示例以及其他一些示例,并且可以在 Go 中成功读取套接字。然而,websocket 服务器似乎并不完全符合典型的开发实践,如在 JS 中使用 .forEach 或 .Each 等方法;导致握手失败。


原版




    package main


    import (

            "fmt"

            "golang.org/x/net/websocket"

            "log"

    )


    var url = "ws://10.0.1.19:5000/data/websocket"


    func main() {

            ws, err := websocket.Dial(url, "", origin)

            if err != nil {

                    log.Fatal(err)

            }


            var msg = make([]byte, 512)

            _, err = ws.Read(msg)

            if err != nil {

                    log.Fatal(err)

            }

            fmt.Printf("Receive: %s\n", msg)

    }


我实际上不需要向套接字发送任何数据,我只需要连接并继续读取它,然后我会将这些数据聚合到单个流中以执行以后的操作。


MMTTMM
浏览 204回答 1
1回答

交互式爱情

启动一个 goroutine 来读取每个连接。将收到的消息发送到频道。从该通道接收以从所有连接获取消息。// Create channel to receive messages from all connectionsmessages := make(chan []byte)// Run a goroutine for each URL that you want to dial.for _, u := range urls {&nbsp; &nbsp; go func(u string) {&nbsp; &nbsp; &nbsp; &nbsp; // Dial with Gorilla package. The x/net/websocket package has issues.&nbsp; &nbsp; &nbsp; &nbsp; c, _, err := websocket.DefaultDialer.Dial(u, http.Header{"Origin":{origin}})&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("dial:", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Clean up on exit from this goroutine&nbsp; &nbsp; &nbsp; &nbsp; defer c.Close()&nbsp; &nbsp; &nbsp; &nbsp; // Loop reading messages. Send each message to the channel.&nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _, m, err := c.ReadMessage()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("read:", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messages <- m&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }(u)}// Print all messages received from the goroutines.for m := range messages {&nbsp; &nbsp; fmt.Printf("%s\n", m)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go