ReadFromUDP不会阻塞

huangapple go评论77阅读模式
英文:

ReadFromUDP does not block

问题

我尝试使用Go构建一个UDP服务器,并发现UDPConn的ReadFromUDP方法不会阻塞线程。我在谷歌上搜索发现有些人面临这个问题,但没有找到解决方法。

我的系统是OSX 10.8.2,Go版本是1.1.1

以下是代码列表:

addr, _ := net.ResolveUDPAddr("udp", "localhost:10234")
conn, err := net.ListenUDP("udp", addr)
if err != nil {
	fmt.Println(err.Error())
	return
}
defer conn.Close()

var buf []byte
for {
	n, remote_addr, _ := conn.ReadFromUDP(buf)
	fmt.Println("from", remote_addr,"got message:", string(buf[:n]))
}

我得到了一个列表:from <nil> got message:

英文:

I tried to build a udp server with go and find that method ReadFromUDP of UDPConn does not block the thread. I google that there are some people facing this problem and no solution found.

my system is osx 10.8.2, go version is 1.1.1

code list bellow

addr, _ := net.ResolveUDPAddr(&quot;udp&quot;, &quot;localhost:10234&quot;)
conn, err := net.ListenUDP(&quot;udp&quot;, addr)
if err != nil {
	fmt.Println(err.Error())
	return
}
defer conn.Close()

var buf []byte
for {
	n, remote_addr, _ := conn.ReadFromUDP(buf)
	fmt.Println(&quot;from&quot;, remote_addr,&quot;got message:&quot;, string(buf[:n]))
}

I got a list of: from &lt;nil&gt; got message:

答案1

得分: 2

我相信在OSX上有一些问题。你的代码,在稍微修改以不忽略错误等,在Linux上运行得很好。

英文:

I believe there's something broken in OSX. Your code, modified only slightly to not ignore errors etc., runs just fine on Linux.

答案2

得分: 2

我将我的系统更新到了osx 10.8.4,上面的代码不起作用。

我将udp服务器代码与我的进行了比较。

并将var buf []byte更改为buf := make([]byte, 1024)

现在它可以正常工作了。

英文:

I updated my system to osx 10.8.4 codes above does not work right.

i compare udp server code with mine.

and change var buf []byte with buf := make([]byte, 1024)

it works well now.

huangapple
  • 本文由 发表于 2013年7月29日 15:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/17918495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定