private void CloseSocket(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            try
            {
                token.Socket.Shutdown(SocketShutdown.Send);
            }
            catch (Exception) { }
            token.Socket.Close();

            Console.WriteLine("Connection to Server is closed.");

            _readWritePool.Push(e);
        }
Ejemplo n.º 2
0
        protected override void ProcessReceive(SocketAsyncEventArgs e)
        {
            bool willRaiseEvent;

            // check if the remote host closed the connection
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                //increment the count of the total bytes receive by the server
                Interlocked.Add(ref _totalBytesRead, e.BytesTransferred);
                Console.WriteLine("The server has read a total of {0} bytes", _totalBytesRead);

                foreach (KeyValuePair <int, SocketAsyncEventArgs> val in _connectedClients)
                {
                    // copy received message to every other client's send buffer
                    SocketAsyncEventArgs args          = val.Value;
                    SocketAsyncEventArgs sendArgs      = _readWritePool.Pop();
                    AsyncUserToken       argsToken     = args.UserToken as AsyncUserToken;
                    AsyncUserToken       sendArgsToken = sendArgs.UserToken as AsyncUserToken;

                    sendArgsToken.Id     = argsToken.Id;
                    sendArgsToken.Socket = argsToken.Socket;
                    Array.Copy(e.Buffer, e.Offset, sendArgs.Buffer, sendArgs.Offset, e.Count);
                    sendArgs.SetBuffer(sendArgs.Offset, e.BytesTransferred);

                    // send message
                    AsyncUserToken token = sendArgs.UserToken as AsyncUserToken;
                    willRaiseEvent = token.Socket.SendAsync(sendArgs);
                    if (!willRaiseEvent)
                    {
                        ProcessSend(sendArgs);
                    }
                }

                // set receive for next message
                willRaiseEvent = (e.UserToken as AsyncUserToken).Socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }
        protected override void ProcessReceive(SocketAsyncEventArgs e)
        {
            // check if the remote host closed the connection
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                Console.WriteLine("The server has sent {0} bytes", e.BytesTransferred);
                string receivedMsg = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                Console.WriteLine("Msg : {0}", receivedMsg);

                bool willRaiseEvent = _socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseSocket(e);
            }
        }
        public void Send(string message)
        {
            // send message async to server.
            SocketAsyncEventArgs writeEventArgs = _readWritePool.Pop();

            byte[] buffer = writeEventArgs.Buffer;
            Array.Clear(buffer, writeEventArgs.Offset, writeEventArgs.BytesTransferred);

            byte[] byteMessage = Encoding.UTF8.GetBytes(message);
            byteMessage.CopyTo(buffer, writeEventArgs.Offset);

            writeEventArgs.SetBuffer(writeEventArgs.Offset, byteMessage.Length);

            AsyncUserToken token = (AsyncUserToken)writeEventArgs.UserToken;

            token.Socket = _socket;
            bool willRaiseEvent = token.Socket.SendAsync(writeEventArgs);

            if (!willRaiseEvent)
            {
                ProcessSend(writeEventArgs);
            }
        }
Ejemplo n.º 5
0
        private void CloseClientSocket(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            // close the socket associated with the client
            try
            {
                token.Socket.Shutdown(SocketShutdown.Send);
            }
            // throws if client process has already closed
            catch (Exception) { }
            token.Socket.Close();

            // decrement the counter keeping track of the total number of clients connected to the server
            Interlocked.Decrement(ref _numConnectedSockets);
            _maxNumberAcceptedClients.Release();
            Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", _numConnectedSockets);

            // remove the client from the connected list
            _connectedClients.TryRemove(token.Id, out e);

            // Free the SocketAsyncEventArg so they can be reused by another client
            _readWritePool.Push(e);
        }