1 回答
TA贡献1712条经验 获得超3个赞
启动一个 goroutine 来读取每个连接。将收到的消息发送到频道。从该通道接收以从所有连接获取消息。
// Create channel to receive messages from all connections
messages := make(chan []byte)
// Run a goroutine for each URL that you want to dial.
for _, u := range urls {
go func(u string) {
// Dial with Gorilla package. The x/net/websocket package has issues.
c, _, err := websocket.DefaultDialer.Dial(u, http.Header{"Origin":{origin}})
if err != nil {
log.Fatal("dial:", err)
}
// Clean up on exit from this goroutine
defer c.Close()
// Loop reading messages. Send each message to the channel.
for {
_, m, err := c.ReadMessage()
if err != nil {
log.Fatal("read:", err)
return
}
messages <- m
}
}(u)
}
// Print all messages received from the goroutines.
for m := range messages {
fmt.Printf("%s\n", m)
}
- 1 回答
- 0 关注
- 203 浏览
添加回答
举报