dongyou8701 2016-10-02 19:57
浏览 439
已采纳

Websocket等待消息超时

I want to create a Websocket connection via GO. This connection follows a clearly defined pattern: The client should "authenticate" (enter data) themself immediately after creating the connection. If the client does not do it, the connection will be closed after a short period.

My current code contains this initial timeout (initTimeout) and the maximum timeout for all connections. While those timers can easily be checked, i am not sure how i can combine the timers with waiting for a message which blocks the execution.

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条回答 默认 最新

  • duanke0555 2016-10-02 22:03
    关注

    Use the read deadline to implement the timeouts:

    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
         // ....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog