deniszykov / WebSocketListener

A lightweight and highly scalable asynchronous WebSocket listener
http://vtortola.github.io/WebSocketListener
81 stars 17 forks source link

[Question] How to tell when client disconnects #49

Open chachew opened 4 years ago

chachew commented 4 years ago

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.");
        }
deniszykov commented 4 years ago

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

chachew commented 4 years ago

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