2016-12-28 121 views
-2

我是golang的新手,我正在通过TCP协议编写客户端 - 服务器应用程序。我需要建立一个临时连接,几秒钟后关闭。我不明白该怎么做。
我有这样的功能,它创造了采空区数据的连接,并等待:设置Golang的连接时间

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

使用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 

如果你想接受呼叫超时,您可以使用TCPListener.SetDeadline方法。

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

或者,你可能对net.Listener计时器呼叫连接上Close()CloseRead(),或Close(),但不会离开你,用洁净的超时错误。

+0

不,这不是我想要的。当我看到这个函数时,如果这些函数是我想要的,我永远不会问这个问题。这个函数只是设置读或写操作的超时时间!但是如果没有它,那么什么都不会发生。 –

+0

@IgniSerpens:那么请举例说明你需要什么。 'Decode'调用将在连接上执行'Read',所以这将导致'Decode'在截止时间到期后返回。 – JimB

+0

我们需要对现有的连接本身进行超时。 –

-1

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