System.Net.Sockets.Socket.Accept C# (CSharp) Method

Accept() public method

public Accept ( ) : Socket
return Socket
        public Socket Accept()
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);

            // Validate input parameters.

            if (CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (_rightEndPoint == null)
            {
                throw new InvalidOperationException(SR.net_sockets_mustbind);
            }

            if (!_isListening)
            {
                throw new InvalidOperationException(SR.net_sockets_mustlisten);
            }

            if (_isDisconnected)
            {
                throw new InvalidOperationException(SR.net_sockets_disconnectedAccept);
            }

            ValidateBlockingMode();
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint}");

            Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint);

            // This may throw ObjectDisposedException.
            SafeCloseSocket acceptedSocketHandle;
            SocketError errorCode = SocketPal.Accept(
                _handle,
                socketAddress.Buffer,
                ref socketAddress.InternalSize,
                out acceptedSocketHandle);

            // Throw an appropriate SocketException if the native call fails.
            if (errorCode != SocketError.Success)
            {
                Debug.Assert(acceptedSocketHandle.IsInvalid);

                // Update the internal state of this socket according to the error before throwing.
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
                throw socketException;
            }

            Debug.Assert(!acceptedSocketHandle.IsInvalid);

            Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
                NetEventSource.Exit(this, socket);
            }
            return socket;
        }

Usage Example

        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                s.Listen(1);
                var ep = (IPEndPoint)s.LocalEndPoint;

                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead);

                    using (Socket server = s.Accept())
                    using (Stream serverStream = new NetworkStream(server, ownsSocket: false))
                    using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                        byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                        serverStream.Write(headerData, 0, headerData.Length);
                    }

                    if (shouldSucceed)
                    {
                        (await getAsync).Dispose();
                    }
                    else
                    {
                        await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                    }
                }
            }
        }
All Usage Examples Of System.Net.Sockets.Socket::Accept