2016-12-28 4 views
-2

私はゴランの初心者です。私はTCPプロトコルを使ってクライアントサーバーアプリケーションを書いています。私は数秒後に終了する一時的な接続をする必要があります。私はそれをする方法を理解していません。 - ない永遠ゴランの接続の時間を設定する

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

使用SetDeadlineまたはSetReadDeadline

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

オプションで、接続にタイマーコールClose()またはCloseRead()を持っている、またはnet.Listener上Close()、それはきれいタイムアウトエラーであなたを残すことはありませんでした。

+0

いいえ、これは私が望むものではありません。私はこの機能を見て、私はこれらの機能が私が望むものならこの質問をしません。この関数は、読み取りまたは書き込み、または両方の操作のタイムアウトを設定するだけです!しかし、それがなければ何も起こりません。 –

+0

@IgniSerpens:必要なものの例を示してください。 'Decode'コールは接続上で' Read'を行います。これにより、デッドラインの期限が切れた後に 'Decode'が返されます。 – JimB

+0

接続自体の既存のタイムアウトを作る必要があります。 –

-1

@JimBはコメントで、標準のnet.Listenerには接続ライフタイムを設定するSetDeadlineメソッドを持つ別のリスナー(net.TCPListener)を使用する必要があります。

関連する問題