How do I broadcast a message to all clients connected on websockets?

blov · · 441 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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, &amp;reply) if err != nil { fmt.Println(&#34;cant read websocket&#34;) break } err = websocket.Message.Send(ws, reply) if err != nil { fmt.Println(&#34;cant send to socket&#34;) 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&#39;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&#39;s net/websocket. But from what I read gorilla is better. Still can&#39;t figure out how to make it work because I&#39;m new to go and don&#39;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(&#34;can&#39;t send to socket&#34;) 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&#39;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&#39;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

441 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传