2016-12-28 127 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沒有它。