在 Golang 中设置连接生命的时间

Ign*_*ens 0 tcp go

我是 golang 的新手,正在通过 TCP 协议编写客户端 - 服务器应用程序。我需要建立一个临时连接,它会在几秒钟后关闭。我不明白该怎么做。
我有一个这样的函数,它创建一个连接并等待 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()
}
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*imB 5

使用SetDeadlineSetReadDeadline

net.Conn文档

    // 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
Run Code Online (Sandbox Code Playgroud)

如果您希望 Accept 调用超时,可以使用该TCPListener.SetDeadline方法。

ln.(*net.TCPListener).SetDeadline(time.Now().Add(time.Second))
Run Code Online (Sandbox Code Playgroud)

或者,你可以有一个计时器调用Close()CloseRead()在连接上,或Close()在net.Listener,但不会离开你,用洁净的超时错误。