Skip to content

[Question] How to tell when client disconnects #49

@chachew

Description

@chachew

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.");
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions