networking - 如何在 net.Conn 上执行非阻塞写入?

标签 networking go nonblocking

如何在 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/

相关文章:

networking - 如何通过 "hostname"在 Docker 容器之间进行通信

windows - 测量 UNC 路径访问时间的工具

linux - 打开命名管道进行写入,并在 select() 中使用

java - 将多个 Java 方法转换为非阻塞线程运行?

ruby - 在 Ruby 中检测按键(非阻塞)w/o getc/gets

android - 在特定网络上重定向 OkHttp3 请求

c++ - 在 C Linux 中通过套接字发送图像 (JPEG)

docker - 无法使用 Go SDK for Docker 推送图像

http - Go Golang 提供特定的 html 文件

go - 字符串到 Go 中的大 Int?