TCP Client switch for reply's

xuanbao · · 495 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So i wrote this up and i am trying to have it read the reply from the server so it can do something using switch but it not working? It will print the message but for some reason its not using the switch?</p> <pre><code> package main import ( &#34;fmt&#34; &#34;net&#34; &#34;bufio&#34; &#34;os&#34; ) var hi bool = false func main() { conn, _ := net.Dial(&#34;tcp&#34;, &#34;127.0.0.1:8080&#34;) for { if hi != true{//first connect fmt.Fprintf(conn, &#34;New&#34; + &#34;\n&#34;) hi = true } message, _ := bufio.NewReader(conn).ReadString(&#39;\n&#39;) switch message{ case &#34;hello&#34;: fmt.Print(&#34;hello&#34;) case &#34;DIE&#34;: fmt.Print(&#34;Die&#34;) os.Exit(0) } fmt.Println(&#34;Message from server: &#34;+ message) } } </code></pre> <hr/>**评论:**<br/><br/>singron: <pre><p><code>ReadString</code> includes the delimiter, so you would have to match on <code>&#34;hello\n&#34;</code> and <code>&#34;DIE\n&#34;</code>.</p> <p>Also, creating multiple bufio Readers from the same connection might lose data. For instance, the first one might read 2 statements into a buffer, you read the first one with ReadString, then the second Reader reads the third statement, and you never see the second statement.</p></pre>SaturnsVoid: <pre><p>I am not sure i understand, Would you be able to show an example, I am a visual learner sometimes :/</p></pre>mcvoid1: <pre><p>What message is printing where? The &#34;New\n&#34; you&#39;re sending to the server? The message printed at the bottom? If the message at the bottom is printing, and it&#39;s &#34;hello&#34; or &#34;Die&#34;, you probably have some whitespace around the string that you should strip. If message is blank or something, you&#39;re probably getting an error from the server or reader that you&#39;re ignoring because you&#39;re dropping the errors instead of checking them.</p></pre>

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

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