Simple golang websocket client example?

agolangf · · 2975 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Does anyone have any example code for a simple websocket client that reads from a websocket server? I have seen a few server examples, but not any clients. (particularly interested in secure wss://, in case there are some special considerations)</p> <p>Further, I&#39;m not really sure what the best websocket library to use is. Seems to be Gorilla is the go to (and not the one by google)?</p> <p>Any help appreciated. Thanks.</p> <hr/>**评论:**<br/><br/>DeedleFake: <pre><p>Does <a href="https://www.godoc.org/golang.org/x/net/websocket#Dial" rel="nofollow">the example from the docs help</a>? If you need TLS, it looks like <code>DialConfig()</code> might be what you&#39;re looking for.</p></pre>: <pre><p>[deleted]</p></pre>Renerte: <pre><p>Code you provided is not a websocket. What you linked is just a simple tcp server. In case you didn&#39;t know, websocket is a protocol used for dynamic communication with http server to help creating dynamic web apps. There is actually an official golang package used for this: <a href="https://godoc.org/golang.org/x/net/websocket" rel="nofollow">https://godoc.org/golang.org/x/net/websocket</a></p></pre>IntellectualReserve: <pre><p>Try looking at the socket.io Go example. </p></pre>moinboin: <pre><p>Here&#39;s how to dial, send and receive with the Gorilla:</p> <pre><code>dialer := websocket.Dialer{ /* set fields as needed */ } ws, _, err := dialer.Dial(&#34;wss://host/path&#34;, nil) if err != nil { // handle error } if err := ws.WriteMessage(websocket.TextMessage, []byte(&#34;hello&#34;)); err != nil { // handle error } _, p, err := ws.ReadMessage() if err != nil { // handle error } fmt.Println(&#34;the message is %s&#34;, p) </code></pre></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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