gpt4 book ai didi

go - tcp 服务器中的空闲超时

转载 作者:IT王子 更新时间:2023-10-29 02:32:04 24 4
gpt4 key购买 nike

我正在使用 Go 语言开发一个项目,其中包括 TCP 服务器。我正在尝试在服务器套接字上实现空闲超时,但无法实现。我使用的 Go 代码是这样的:

package main

import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"time"
)

func main() {
startServer(6666, time.Duration(2)*time.Second)
}

func startServer(port int, deadline time.Duration) {
// Listen for incoming connections.
strPort := strconv.Itoa(port)
l, err := net.Listen("tcp", ":"+strPort)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
fmt.Println("Listening on port:" + strPort)
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}

fmt.Println("Got new connection")

// Set read timeout
conn.SetReadDeadline(time.Now().Add(deadline))

// Handle connections in a new goroutine.
go handleRequest(conn)
}
}

func handleRequest(conn net.Conn) {
reader := bufio.NewReader(conn)
scanner := bufio.NewScanner(reader)

for scanner.Scan() {
fmt.Println(scanner.Bytes())
}
}

我希望它超时 并在 2 秒后关闭连接。谁能告诉我我可能做错了什么。为了测试它,我使用了一个我用 Python scipt 编写的 TCP 客户端。客户端代码如下:

λ python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from socket import *
>>> c = socket(family=AF_INET, type=SOCK_STREAM)
>>> c.connect(('localhost', 6666))

我总是可以跟踪所有打开的连接,以及它们在某种数据结构中的最后事件时间,并启动一个 goroutine,它定期检查每个连接耗时,关闭我没有收到的连接一会儿。但我想利用内置方法 SetReadDeadline() 来完成这项工作。

最佳答案

SetDeadlinenet 包文档中,它指出

   // An idle timeout can be implemented by repeatedly extending
// the deadline after successful Read or Write calls.

您可以通过创建自己的 net.Conn 类型来实现您希望超时的调用。由于空闲连接通常会在 Read 中等待,因此您通常要在此处设置截止时间。

type Conn struct {
net.Conn
idleTimeout time.Duration
}

func (c *Conn) Read(b []byte) (int, error) {
err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
if err != nil {
return 0, err
}
return c.Conn.Read(b)
}

关于go - tcp 服务器中的空闲超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com