<p>I need to run websocket.Message.Send(ws, reply) but it only replies to one socket. How do I broadcast the message to all websockets?</p>
<pre><code> func handleWebsocket(ws *websocket.Conn) {
for {
var reply string
err := websocket.Message.Receive(ws, &reply)
if err != nil {
fmt.Println("cant read websocket")
break
}
err = websocket.Message.Send(ws, reply)
if err != nil {
fmt.Println("cant send to socket")
break
}
}
}
</code></pre>
<hr/>**评论:**<br/><br/>styluss: <pre><p>You need to register somewhere the websockets that are connected and send to all of them. Don't forget to clean up after the user disconnects.</p></pre>lstokeworth: <pre><p>See <a href="https://github.com/gorilla/websocket/tree/master/examples/chat" rel="nofollow">the Gorilla chat example</a>.</p></pre>xDinomode: <pre><p>Actually I was attempting to do it with go's net/websocket. But from what I read gorilla is better. Still can't figure out how to make it work because I'm new to go and don't really understand goroutines or channels. </p></pre>lstokeworth: <pre><p>You will need to learn about groutines to solve this problem. </p></pre>TheMerovius: <pre><pre><code>for _, ws := range websockets {
if err = websocket.Message.Send(ws, reply); err != nil {
fmt.Println("can't send to socket")
break
}
}
</code></pre></pre>xiegeo: <pre><p>That break will break on the first websocket that was disconnected and not send the message to any websockets after it. Also I would consider doing each send in its own go routine, or use buffered channels, since send can block.</p></pre>Matthias247: <pre><p>Yes, and the next problem would be how the websockets array is created. If it's manipulated from multiple goroutines it must be thread safe. And calling the code inside a mutex is probably not the best idea, since the array might then be locked for a longer timeframe (until all messages are sent). </p></pre>buckhx: <pre><p>Yeah that response really shouldn't be getting upvoted...</p></pre>swiddie: <pre><p>Oh the day the web opens up for udp multicast for regular users. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传