예제 #1
0
        public virtual async ValueTask <IConnection> AcceptAsync(CancellationToken cancellationToken = default)
        {
            using (cancellationToken.Register(_listenerCancellationCallback))
            {
                while (true)
                {
                    try
                    {
                        var socket = await _listener.AcceptSocketAsync();

                        _logger.SocketAccepted(socket.RemoteEndPoint, socket.LocalEndPoint);
                        return(_options.CreateConnection(socket));
                    }
                    catch (ObjectDisposedException)
                    {
                        // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                        return(null);
                    }
                    catch (SocketException e) when(e.SocketErrorCode == SocketError.OperationAborted)
                    {
                        // A call was made to UnbindAsync/DisposeAsync just return null which signals we're done
                        return(null);
                    }
                    catch (InvalidOperationException)
                    {
                        // Stopping the server immediately can cause this exception
                        // "Not listening. You must call the Start() method before calling this method."
                        return(null);
                    }
                    catch (SocketException)
                    {
                        // The connection got reset while it was in the backlog, so we try again.
                        _logger.ConnectionReset(connectionId: "(null)");
                    }
                }
            }
        }