Websocket等待消息与超时

时间:2016-10-02 19:57:50

标签: go

我想通过GO创建一个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?
    }
}

1 个答案:

答案 0 :(得分: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
     // ....
}