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

时间:2016-12-28 05:49:19

标签: go tcp

我是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()
}

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

2 个答案:

答案 0 :(得分:3)

使用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(),或在net.Listener上设置Close(),但这不会让您更加清洁超时错误。

答案 1 :(得分:0)

正如@JimB在评论中所说,我们需要使用另一个监听器--net.TCPListener,它有方法SetDeadline,设置连接生命周期,而标准net.Listener没有。