Example #1
0
        /// <summary>
        ///     SocketAsyncEventArgs object that will do receive/send.
        /// </summary>
        /// <param name="args"> </param>
        private void ProcessAccept(SocketAsyncEventArgs args)
        {
            _monitor.ProcessAccept();

            // Loop back to post another accept op.
            StartAccept();

            // This is when there was an error with the accept op.
            if (args.SocketError != SocketError.Success)
            {
                CloseClientSocket(args.AcceptSocket, args);
            }
            else
            {
                // Get a SocketAsyncEventArgs object from the pool of receive/send op //SocketAsyncEventArgs objects
                SocketAsyncEventArgs clientArgs;
                if (!_clientArgsPool.TryPop(out clientArgs))
                {
                    clientArgs = new SocketAsyncEventArgs();
                    var buffer = new byte[_settings.BufferSize];
                    clientArgs.SetBuffer(buffer, 0, buffer.Length);
                    clientArgs.Completed += SocketOperationCompleted;
                    _protocol.InitState(clientArgs);
                }

                // A new socket was created by the AcceptAsync method. The
                // SocketAsyncEventArgs object which did the accept operation has that
                // socket info in its AcceptSocket property. Now we will give
                // a reference for that socket to the SocketAsyncEventArgs object which will do receive/send.
                clientArgs.AcceptSocket = args.AcceptSocket;

                // We handed off the connection info from the accepting socket to the receiving socket.
                StartReceive(clientArgs);
            }

            // Clear the socket info from that object, so it will be ready for a new socket when it comes out of the pool.
            args.AcceptSocket = null;
            _acceptArgsPool.Push(args);
        }