Single Server Listening on Multiple Ports

agolangf · · 677 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I want to make a simple chat server that listens on multiples ports and sends messages from one port to the other. I have already played around with an echo server, but I do not really know how to go beyond that without connecting to multiple ports. </p> <p>How do I use net.Listen() to connect to more than 1 port? Is there a better way to go about this?</p> <hr/>**评论:**<br/><br/>nhooyr: <pre><p>you could just launch 3 goroutines that listen on the ports and accept connections. </p> <p>I&#39;m not sure exactly what you&#39;re trying to do but last year when I was learning go I created a simple chat server you might find useful. </p> <p><a href="https://github.com/nhooyr/simple-chat/blob/master/cserver/main.go" rel="nofollow">https://github.com/nhooyr/simple-chat/blob/master/cserver/main.go</a></p></pre>sethammons: <pre><p>I would spin up multiple goroutines, each listening on the port you want. Then they can each in turn send on a channel to a central fan-in / select statement. You could also fan out from there to the separate routines if needed. </p> <p>Check out some patterns here: <a href="https://talks.golang.org/2012/concurrency.slide#1" rel="nofollow">https://talks.golang.org/2012/concurrency.slide#1</a> (maybe look around slide 27 or 28).</p> <p>Just my initial thought without ever having made a chat server. </p></pre>jeffrallen: <pre><p>Yes to the previous posters. They didn&#39;t mention the underlying principle, however. Go&#39;s networking functions are blocking. When you call Accept() in a server, it blocks right there until the next connection arrives. If you call Read() on that connection, that Read will block until bytes arrive from the client. If you are blocked in Read, you can&#39;t be accepting your next connection. Blockage everywhere.</p> <p>Which is why networking code in Go is typically written with one goroutine per listening port, and once a connection arrives, at least one goroutine per connection. Some designs reasonably call for a reader and a writer goroutine per connection. So every call which blocks is allowed to block. The other goroutines in the system keep doing their thing, either computing, or more likely being blocked on something else and waking up later independently. This is a huge difference between Go and Node.js, and between Go and the vast majority of C servers, which need to use an event loop to avoid blocking.</p> <p>But if you start a goroutine, you need to be sure you know when it will end. Read up some more until you understand that piece of advice, or come back and ask for more info and we&#39;ll be here to help. :)</p> <p>-jeff</p></pre>

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

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