2016-10-02 3 views
1

GO経由でWebsocket接続を作成します。この接続は明確に定義されたパターンに従います。クライアントは、接続を作成した直後に自分自身を「認証」(データ入力)する必要があります。クライアントがそれをしない場合、接続は短期間で終了します。タイムアウトでメッセージを待っているWebsocket

現在のコードには、この初期タイムアウト(initTimeout)とすべての接続の最大タイムアウトが含まれています。これらのタイマーは簡単にチェックすることができますが、実行をブロックするメッセージを待ってタイマーを組み合わせる方法がわかりません。

ws, err := upgrader.Upgrade(w, r, nil) 
initTimeout := time.NewTicker(time.Duration(30) * time.Second) 
maxTimeout := time.NewTicker(time.Duration(45) * time.Minute) 

for { 
    select { 
     case <- initTimeout.C: 
      ws.WriteMessage(websocket.TextMessage, []byte("No input received")) 
      ws.Close() 
     case <- maxTimeout.C: 
      ws.WriteMessage(websocket.TextMessage, []byte("Maximum timeout")) 
      ws.Close() 
     default: 
      mt, message, err := c.ReadMessage() 
      // will this block the timers? 
    } 
} 

答えて

2

タイムアウトを実装するためにread deadlineを使用します。

ws, err := upgrader.Upgrade(w, r, nil) 
if err != nil { 
    // handle error 
} 

// Read the initial message with deadline of 30 seconds 
ws.SetReadDeadline(time.Now().Add(30 * time.Second)) 
mt, message, err := c.ReadMessage() 
if err != nil { 
    // Handle the error which might be a deadline exceeded error. 
} 
// process the initial message 
// ... 

for { 
    // Read next message with deadline of 45 minutes 
    ws.SetReadDeadline(time.Now().Add(45 * time.Minute)) 
    mt, message, err = c.ReadMessage() 
    if err != nil { 
     // Handle the error which might be a deadline exceeded error. 
    } 
    // process message 
    // .... 
} 
関連する問題