WebSocketListener icon indicating copy to clipboard operation
WebSocketListener copied to clipboard

[Question] How to tell when client disconnects

Open chachew opened this issue 6 years ago • 2 comments

How do i know when a client closes its socket connection?

public async Task AcceptWebSocketsAsync(WebSocketListener server, CancellationToken cancellation)
        {
            await Task.Yield();

            while (!cancellation.IsCancellationRequested)
            {
                try
                {
                    var webSocket = await server.AcceptWebSocketAsync(cancellation).ConfigureAwait(false);
                    if (webSocket == null)
                    {
                        if (cancellation.IsCancellationRequested || !server.IsStarted) break; // stopped
                        continue; // retry
                    }

                    await WebSocketHandler.OnConnected(webSocket, 123);

                    #pragma warning disable 4014
                    EchoAllIncomingMessagesAsync(webSocket, cancellation);
                    #pragma warning restore 4014
                }
                catch (OperationCanceledException)
                {
                    /* server is stopped */
                    break;
                }
                catch (Exception)
                {
                    //Log.Error("An error occurred while accepting client.", acceptError);
                }
            }

            //Log.Warning("Server has stopped accepting new clients.");
        }

chachew avatar Dec 05 '19 15:12 chachew

Hi @chachew! webSocket has IsConnected property. And null message is received on remote party disconnect.

deniszykov avatar Dec 11 '19 18:12 deniszykov

Thanks, i ended up figuring that out after some messing around with it.

chachew avatar Dec 13 '19 16:12 chachew