gpt4 book ai didi

go - 在 Golang 中设置连接生命周期的时间

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

我是golang的新手,我正在通过TCP协议(protocol)编写一个客户端-服务器应用程序。我需要建立一个临时连接,该连接将在几秒钟后关闭。我不明白该怎么做。
我有一个这样的函数,它创建一个连接并等待 gob 数据:

    func net_AcceptAppsList(timesleep time.Duration) {
ln, err := net.Listen("tcp", ":"+conf.PORT)
CheckError(err)
conn, err := ln.Accept()
CheckError(err)
dec := gob.NewDecoder(conn)
pack := map[string]string{}
err = dec.Decode(&pack)
fmt.Println("Message:", pack)
conn.Close()
}

我需要让这个函数只等待几秒钟的数据——而不是永远。

最佳答案

使用SetDeadlineSetReadDeadline

来自net.Conn docs

    // SetDeadline sets the read and write deadlines associated
// with the connection. It is equivalent to calling both
// SetReadDeadline and SetWriteDeadline.
//
// A deadline is an absolute time after which I/O operations
// fail with a timeout (see type Error) instead of
// blocking. The deadline applies to all future I/O, not just
// the immediately following call to Read or Write.
//
// An idle timeout can be implemented by repeatedly extending
// the deadline after successful Read or Write calls.
//
// A zero value for t means I/O operations will not time out.
SetDeadline(t time.Time) error

// SetReadDeadline sets the deadline for future Read calls.
// A zero value for t means Read will not time out.
SetReadDeadline(t time.Time) error

// SetWriteDeadline sets the deadline for future Write calls.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means Write will not time out.
SetWriteDeadline(t time.Time) error

如果你想让 Accept 调用超时,你可以使用 TCPListener.SetDeadline方法。

ln.(*net.TCPListener).SetDeadline(time.Now().Add(time.Second))

可选地,您可以在连接上调用计时器 Close()CloseRead(),或者在网络上调用 Close() .Listener,但这不会给您留下更清晰的超时错误。

关于go - 在 Golang 中设置连接生命周期的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356088/

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