如何为WebSocket.ReceiveAsync设置超时

时间:2017-03-19 23:42:58

标签: websocket

似乎WebSocket.ReceiveAsync可能永远等待数据。有没有办法设置不活动超时?以下是概念上代码的外观:

public async Task DoListening(AspNetWebSocketContext context)
{
    WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
    if (inactivity timeout ocurred)
    {
        DoInactivityAction();
    }
    else
    {
        DoReceiveAction();
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用自定义cancellation token with timeout

public async Task DoListening(AspNetWebSocketContext context)
{
    var timeOut = new CancellationTokenSource(500).Token;
    WebSocketReceiveResult receiveResult;
    try
    {
        receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), timeOut );
        DoReceiveAction();
    }
    catch(OperationCancelledException)
    {
        DoInactivityAction();
    }
}

未经测试的代码。