提交响应后,无法执行WebSocket操作

时间:2017-04-01 16:23:15

标签: c# http websocket handshake

我遇到了一个问题,即通过APIController实现Web套接字连接。 我将HTTP请求升级到不同的协议,并且它可以正常工作。

var owinContext = Request.GetOwinContext();
var acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");
if (acceptToken != null)
{
    SocketConnection.Setter(tenantId);
    acceptToken(null, SocketConnection.Process);
}
else
{
    return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);

可以打开连接并正确关闭它,没有任何问题。 当我正在检查 WebSocketReceiveResult 时会出现问题,所以我知道何时关闭我的连接。

public static async Task Process(IDictionary<string, object> websocketContext)
{
    object value;
    System.Net.WebSockets.WebSocket socket = null;

    if (websocketContext.TryGetValue(typeof(WebSocketContext).FullName, out value))
    {
        socket = ((WebSocketContext)value).WebSocket;
    }        

    var buffer = new ArraySegment<byte>(new byte[1024]);

    while (socket != null && socket.State == WebSocketState.Open)
    {
        WebSocketReceiveResult result;
        do
        {
            // The following line
            result = await socket.ReceiveAsync(buffer, CancellationToken.None);

        } while (!result.EndOfMessage);

        if (result.MessageType != WebSocketMessageType.Close) continue;

        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
    }     
}

执行此操作时会出现此问题:

提交回复后无法执行此操作

0 个答案:

没有答案