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

huangapple go评论88阅读模式
英文:

Set the time for connection's life in Golang

问题

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

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

英文:

I am a novice in golang and I am writing a client-server application through the TCP protocol. I need to make a temporary connection, which will close after a couple of seconds. I don't understand how to do that.
I have a such function, which creates a connection and waits for gob data:

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

I need to make this function to wait for data for only some seconds - not forever.

答案1

得分: 6

使用SetDeadlineSetReadDeadline

net.Conn文档中:

// SetDeadline设置与连接关联的读取和写入截止时间。它等效于同时调用SetReadDeadline和SetWriteDeadline。

// 截止时间是一个绝对时间,在此之后,I/O操作将超时失败(参见类型Error),而不是阻塞。截止时间适用于所有未来的I/O操作,而不仅仅是紧接着的Read或Write调用。

// 可以通过在成功的Read或Write调用之后重复延长截止时间来实现空闲超时。

// t的零值表示I/O操作不会超时。
SetDeadline(t time.Time) error

// SetReadDeadline设置未来Read调用的截止时间。
// t的零值表示Read不会超时。
SetReadDeadline(t time.Time) error

// SetWriteDeadline设置未来Write调用的截止时间。
// 即使写入超时,它也可能返回n>0,表示某些数据已成功写入。
// t的零值表示Write不会超时。
SetWriteDeadline(t time.Time) error

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

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

或者,您可以在连接上调用计时器的Close()CloseRead()方法,或者在net.Listener上调用Close()方法,但这样做不会给出更清晰的超时错误。

英文:

Use SetDeadline or SetReadDeadline

From the 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

If you want the Accept call to timeout, you can use the TCPListener.SetDeadline method.

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

Optionally, you could have a timer call Close() or CloseRead() on the connection, or Close() on the net.Listener, but that won't leave you with the cleaner timeout error.

答案2

得分: 0

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

英文:

As @JimB said in comments, we need to use another listener - net.TCPListener, which have method SetDeadline, setting the connection lifetime, while the standart net.Listener doesn't have it.

huangapple
  • 本文由 发表于 2016年12月28日 13:49:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/41356088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定