System.Net.WebSockets Connection OPEN before server is listening

196 views Asked by At

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?

1

There are 1 answers

0
Nico On BEST ANSWER

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.