简体   繁体   English

如何检查从 tcp 套接字读取是否会阻塞?

[英]How can I check if reading from a tcp socket will block?

If I have a tcp connection conn , how can determine whether conn.Read will block?如果我有一个 tcp 连接conn ,如何确定conn.Read是否会阻塞?

My understanding is that Go's Read uses non-blocking sockets and will only block if there's no data available to read (See https://stackoverflow.com/a/36117724/4447365 ).我的理解是 Go 的 Read 使用非阻塞套接字,并且只有在没有可读取的数据时才会阻塞(参见https://stackoverflow.com/a/36117724/4447365 )。

But is there any way to check if the socket has no data available?但是有没有办法检查套接字是否没有可用数据?

This can be done with the POSIX read function by calling it with a count argument of zero.这可以通过 POSIX读取函数完成,方法是使用count参数为零来调用它。

When programming in Go don't worry about it.在 Go 中编程时不要担心。 Assume everything will block.假设一切都会阻塞。 Then put it in a goroutine so it runs asynchronously anyway.然后把它放在一个 goroutine 中,所以它无论如何都是异步运行的。

The Go runtime handles all of the details. Go 运行时处理所有细节。

Also, the issue here seems to be what you want to do.此外,这里的问题似乎是您想要做什么。 The issue was rejected: Go doesn't do that.这个问题被拒绝了:Go 不会那样做。 Neither does C. And even if it did it isn't reliable. C 也没有。即使它做了它也不可靠。 If you read down to the end there are suggested solutions involving the Linger TCP setting.如果您读到最后,有一些建议的解决方案涉及Linger TCP 设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM