2016-10-02 311 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 
    // .... 
}