在 Golang 中检测 TCP 超时方法:使用 SetReadDeadline 和 SetWriteDeadline 设置读/写超时。执行读/写操作时,超时过后会返回 net.Error,其中 Timeout 方法返回 true,表示已超时。

如何判断 Golang 中的 TCP 超时
在 Golang 中,可以通过设置读/写超时来判断 TCP 连接是否超时。
设置超时
使用 net.Conn 接口的 SetReadDeadline 和 SetWriteDeadline 方法设置超时:
立即学习“go语言免费学习笔记(深入)”;
<code class="go">conn.SetReadDeadline(time.Now().Add(timeout)) conn.SetWriteDeadline(time.Now().Add(timeout))</code>
其中 timeout 是超时时间,单位为纳秒。
检查超时
执行读/写操作时,如果超时已过则会返回 net.Error 错误,其中 Timeout 方法返回 true:
<code class="go">_, err := conn.Read(buf)
if err != nil && err.(net.Error).Timeout() {
// 超时
}</code>代码示例
以下代码示例展示了如何在 TCP 连接上设置并检查超时:
<code class="go">package main
import (
"log"
"net"
"time"
)
func main() {
// 创建 TCP 连接
conn, err := net.Dial("tcp", ":80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// 设置超时
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
// 发送数据
_, err = conn.Write([]byte("Hello, world!"))
if err != nil {
if err.(net.Error).Timeout() {
log.Println("发送数据超时")
} else {
log.Fatal(err)
}
}
// 接收数据
buf := make([]byte, 1024)
_, err = conn.Read(buf)
if err != nil {
if err.(net.Error).Timeout() {
log.Println("接收数据超时")
} else {
log.Fatal(err)
}
}
}</code>以上就是golang怎么判断tcp超时的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号