如何在 Go 中对网络连接执行非阻塞写入?
我认为通过设置过去的截止日期可能可以做到这一点:
conn.SetWriteDeadline(time.Date(0, 0, 0, 0, 0, 0, 1, time.UTC))
n, err := conn.Write(buffer)
...但这只是失败并出现“i/o 超时”错误,实际上没有向连接写入任何字节。
最佳答案
在 Go 中,您使用阻塞 I/O,运行时将其“转换”为非阻塞 I/O:从套接字读取数据时被阻塞的 goroutine 将被调度程序与另一个准备好继续执行的 goroutine 交换。
因此,您可以两全其美:更易于遵循的代码(例如,没有回调 hell )和非阻塞 I/O 的效率(即 epoll、kqueue、完成端口)。
更新:
@cpcallen I need to be able to write to a socket in such a way that I can be certain that the thread performing the write does not block.
如果通过“线程”引用操作系统级别的线程,它不会被阻塞。如果通过“线程”你指的是执行写入的 goroutine,那还不可能,但有一个建议:https://github.com/golang/go/issues/15735
关于networking - 如何在 net.Conn 上执行非阻塞写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44209241/