Search code examples
c#websocketsystem.net.websockets

System.Net.WebSockets Connection OPEN before server is listening


I'm running into issues on a setup that's under load accepting the connection and setting it to OPEN before the server is read to read from the socket.

Example(not the actual code):

while (true) {
    var objContext = HttpListenerContext.GetContext();
    if (objContext.Request.IsWebSocketRequest){
        var WebSocket = (await HttpListenerContext.AcceptWebSocketAsync(null)).WebSocket;
        while (WebSocket.State == WebSocketState.Open) {
            var buffer = new byte[BUFFERSIZE];
            var result = await WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken);
            ....
        }
    } 
}

When adding breakpoints on the client and server I've noticed after the AcceptWebSocketAsync is called, the clients receives that the connection is 'OPEN' and ready to be used and starts sending data.

The issue is that ReceiveAsync hasn't started at that time yet, reason is that the ReceiveAsync is a bit slower to start running the task, they stay in WaitingForActivation a bit longer then on an idle system due to the server in question being under high load (lots of other tasks/threads and low number of cpu's).

Is this normal behavior and how can this be stopped?


Solution

  • Had someone go over my code, that person found that the ReceiveAsync being called later isn't an issue, the info is in the buffer.
    It was higher up that an event handler was attached too late.