/// <summary>
 /// Dequeuer. Read the receive queue and raise the receive event for each message
 /// </summary>
 /// <param name="stateObj">The received message</param>
 protected virtual void ReceiveDequeuer()
 {
     while (!this.flagShutdown)
     {
         ReceiveMessageStateObject message = null;
         try
         {
             message = receiveQueue.Take(this.cancellationToken.Token);
         }
         catch (OperationCanceledException ex)
         {
             Trace.WriteLine("A cancel operation was request. A shutdown will be done.");
             this.flagShutdown = true;
         }
         if (flagShutdown)
         {
             break;
         }
         if (message != null)
         {
             //Trace.WriteLine(string.Format("Remove Message {0} Client {1} from the receive queue and raise event", message.Message.MessageUID, message.Message.ClientUID));
             message.Handler.RaiseReceiveMessageEvent(message);
         }
     }
 }
 /// <summary>
 /// Dequeuer. Read the receive queue and raise the receive event for each message
 /// </summary>
 /// <param name="stateObj">The received message</param>
 protected virtual void ReceiveDequeuer()
 {
     while (!this.flagShutdown)
     {
         ReceiveMessageStateObject message = null;
         try
         {
             message = receiveQueue.Take(this.cancellationToken.Token);
         }
         catch (OperationCanceledException ex)
         {
             Trace.WriteLine("A cancel operation was request. A shutdown will be done.");
             this.flagShutdown = true;
         }
         if (flagShutdown)
         {
             OnCloseConnection(this);
             break;
         }
         if (message != null)
         {
             message.Handler.RaiseReceiveMessageEvent(message);
         }
     }
 }
 /// <summary>
 /// Raise a received message event. This method is running in the same thread of the caller.
 /// </summary>
 /// <param name="stateObj">The receive message state object</param>
 protected void RaiseReceiveMessageEvent(object stateObj)
 {
     if (receiveMessageEvent != null)
     {
         ReceiveMessageStateObject rcvObj = (ReceiveMessageStateObject)stateObj;
         receiveMessageEvent(rcvObj.Handler, rcvObj.Message);
     }
 }
 /// <summary>
 /// Handle a received message. A received message event is raise but in a new thread in order to not block the main thread.
 /// Override this method to change the behavior.
 /// </summary>
 /// <param name="rcvObj">The received object</param>
 protected virtual void OnReceiveMessage(ReceiveMessageStateObject rcvObj)
 {
     if (this.receiveQueue != null)
     {
         this.receiveQueue.Add(rcvObj);
         return;
     }
     ThreadPool.QueueUserWorkItem(new WaitCallback(rcvObj.Handler.RaiseReceiveMessageEvent), rcvObj);
 }
 /// <summary>
 /// Handle a received message. A received message event is raise but in a new thread in order to not block the main thread.
 /// Override this method to change the behavior.
 /// </summary>
 /// <param name="rcvObj">The received object</param>
 protected virtual void OnReceiveMessage(ReceiveMessageStateObject rcvObj)
 {
     if (this.receiveQueue != null)
     {
         //Trace.WriteLine(string.Format("Add Message {0} from Client {1} in the receive queue", rcvObj.Message.MessageUID, rcvObj.Message.ClientUID));
         this.receiveQueue.Add(rcvObj);
         return;
     }
     ThreadPool.QueueUserWorkItem(new WaitCallback(rcvObj.Handler.RaiseReceiveMessageEvent), rcvObj);
 }
        /// <summary>
        /// Callback for asynchronous receiving.
        /// </summary>
        /// <param name="ar">The socket state object for receiving data</param>
        private static void ProcessReceive(SocketAsyncEventArgs e)
        {
            AbstractAsyncTcpSocketClientHandler handler = (AbstractAsyncTcpSocketClientHandler)e.UserToken;

            try
            {
                while (true)
                {
                    //Trace.WriteLine(string.Format("Receive {0} bytes", e.BytesTransferred));
                    if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                    {
                        int read = e.BytesTransferred;
                        // Fire event for incoming message
                        handler.OnReceivingMessage(handler);
                        while (true)
                        {
                            AbstractMessage message = AbstractMessage.TryReadMessage(handler.GetMessageInstance(), handler.stateObject, read);
                            // Fire event for received message
                            if (message != null)
                            {
                                ReceiveMessageStateObject rcvObj = new ReceiveMessageStateObject()
                                {
                                    Handler = handler, Message = message
                                };
                                handler.OnReceiveMessage(rcvObj);
                            }
                            if (handler.stateObject.pendingBuffer == null)
                            {
                                break;
                            }
                            read = 0;
                        }
                        bool flagPending = ((TcpSocketAsync)handler.socket).ReceiveAsync(e);
                        if (flagPending)
                        {
                            break;
                        }
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("SocketError {0}.", e.SocketError));
                        handler.Close();
                        break;
                    }
                }
            }
            catch (MessageException mex)
            {
                // Invalid message
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", mex));
                handler.Close();
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode == SocketError.ConnectionReset || sex.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    Trace.WriteLine(string.Format("Socket error for disconnection {0} : {1} : {2}. Client will be disconnected", sex.ErrorCode, sex.SocketErrorCode, sex.Message));
                    handler.stateObject.message       = null;
                    handler.stateObject.pendingBuffer = null;
                    handler.Close();
                }
                else
                {
                    Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", sex));
                    handler.stateObject.message       = null;
                    handler.stateObject.pendingBuffer = null;
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", ex));
                handler.stateObject.message       = null;
                handler.stateObject.pendingBuffer = null;
                handler.Close();
            }
        }
        /// <summary>
        /// Callback for asynchronous receiving.
        /// </summary>
        /// <param name="ar">The socket state object for receiving data</param>
        protected static void ReadCallback(IAsyncResult ar)
        {
            SocketStateObject state = (SocketStateObject)ar.AsyncState;
            AbstractTcpSocketClientHandler handler = state.workHandler;

            try
            {
                // Read data from the client socket.
                int read = handler.EndReceive(ar);
                Trace.WriteLine(string.Format("Receive {0} bytes", read));

                // Data was read from the client socket.
                if (read > 0)
                {
                    // Fire event for incoming message
                    handler.OnReceivingMessage(handler);
                    while (true)
                    {
                        AbstractMessage message = AbstractMessage.TryReadMessage(handler.GetMessageInstance(), state, read);
                        // Fire event for received message
                        if (message != null)
                        {
                            ReceiveMessageStateObject rcvObj = new ReceiveMessageStateObject() { Handler = handler, Message = message };
                            handler.OnReceiveMessage(rcvObj);
                        }
                        if (state.pendingBuffer == null)
                        {
                            break;
                        }
                        read = 0;
                    }
                    handler.socket.BeginReceive(state, new AsyncCallback(ReadCallback));
                }
                else
                {
                    handler.Close();
                }
            }
            catch (MessageException mex)
            {
                // Invalid message
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", mex));
                state.message = null;
                state.pendingBuffer = null;
                handler.Close();
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode == SocketError.ConnectionReset || sex.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    Trace.WriteLine(string.Format("Socket error for disconnection {0} : {1} : {2}. Client will be disconnected", sex.ErrorCode, sex.SocketErrorCode, sex.Message));
                    state.message = null;
                    state.pendingBuffer = null;
                    handler.Close();
                }
                else
                {
                    Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", sex));
                    state.message = null;
                    state.pendingBuffer = null;
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", ex));
                state.message = null;
                state.pendingBuffer = null;
                handler.Close();
            }
        }
 /// <summary>
 /// Handle a received message. A received message event is raise but in a new thread in order to not block the main thread.
 /// Override this method to change the behavior.
 /// </summary>
 /// <param name="rcvObj">The received object</param>
 protected virtual void OnReceiveMessage(ReceiveMessageStateObject rcvObj)
 {
     if (this.receiveQueue != null)
     {
         Trace.WriteLine(string.Format("Add Message {0} from Client {1} in the receive queue", rcvObj.Message.MessageUID, rcvObj.Message.ClientUID));
         this.receiveQueue.Add(rcvObj);
         return;
     }
     ThreadPool.QueueUserWorkItem(new WaitCallback(rcvObj.Handler.RaiseReceiveMessageEvent), rcvObj);
 }
        /// <summary>
        /// Callback for asynchronous receiving.
        /// </summary>
        /// <param name="ar">The socket state object for receiving data</param>
        protected static void ReadCallback(IAsyncResult ar)
        {
            SocketStateObject state = (SocketStateObject)ar.AsyncState;
            AbstractTcpSocketClientHandler handler = state.workHandler;

            try
            {
                // Read data from the client socket.
                int read = handler.EndReceive(ar);
                Trace.WriteLine(string.Format("Receive {0} bytes", read));

                // Data was read from the client socket.
                if (read > 0)
                {
                    // Fire event for incoming message
                    handler.OnReceivingMessage(handler);
                    while (true)
                    {
                        AbstractMessage message = AbstractMessage.TryReadMessage(handler.GetMessageInstance(), state, read);
                        // Fire event for received message
                        if (message != null)
                        {
                            ReceiveMessageStateObject rcvObj = new ReceiveMessageStateObject()
                            {
                                Handler = handler, Message = message
                            };
                            handler.OnReceiveMessage(rcvObj);
                        }
                        if (state.pendingBuffer == null)
                        {
                            break;
                        }
                        read = 0;
                    }
                    handler.socket.BeginReceive(state, new AsyncCallback(ReadCallback));
                }
                else
                {
                    handler.Close();
                }
            }
            catch (MessageException mex)
            {
                // Invalid message
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", mex));
                state.message       = null;
                state.pendingBuffer = null;
                handler.Close();
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode == SocketError.ConnectionReset || sex.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    Trace.WriteLine(string.Format("Socket error for disconnection {0} : {1} : {2}. Client will be disconnected", sex.ErrorCode, sex.SocketErrorCode, sex.Message));
                    state.message       = null;
                    state.pendingBuffer = null;
                    handler.Close();
                }
                else
                {
                    Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", sex));
                    state.message       = null;
                    state.pendingBuffer = null;
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", ex));
                state.message       = null;
                state.pendingBuffer = null;
                handler.Close();
            }
        }
        /// <summary>
        /// Callback for asynchronous receiving.
        /// </summary>
        /// <param name="ar">The socket state object for receiving data</param>
        private static void ProcessReceive(SocketAsyncEventArgs e)
        {
            AbstractAsyncTcpSocketClientHandler handler = (AbstractAsyncTcpSocketClientHandler)e.UserToken;

            try
            {
                while (true)
                {
                    Trace.WriteLine(string.Format("Receive {0} bytes", e.BytesTransferred));
                    if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                    {
                        int read = e.BytesTransferred;
                        // Fire event for incoming message
                        handler.OnReceivingMessage(handler);
                        while (true)
                        {
                            AbstractMessage message = AbstractMessage.TryReadMessage(handler.GetMessageInstance(), handler.stateObject, read);
                            // Fire event for received message
                            if (message != null)
                            {
                                ReceiveMessageStateObject rcvObj = new ReceiveMessageStateObject() { Handler = handler, Message = message };
                                handler.OnReceiveMessage(rcvObj);
                            }
                            if (handler.stateObject.pendingBuffer == null)
                            {
                                break;
                            }
                            read = 0;
                        }
                        bool flagPending = ((TcpSocketAsync)handler.socket).ReceiveAsync(e);
                        if (flagPending)
                        {
                            break;
                        }
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("SocketError {0}.", e.SocketError));
                        handler.Close();
                        break;
                    }
                }
            }
            catch (MessageException mex)
            {
                // Invalid message
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", mex));
                handler.Close();
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode == SocketError.ConnectionReset || sex.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    Trace.WriteLine(string.Format("Socket error for disconnection {0} : {1} : {2}. Client will be disconnected", sex.ErrorCode, sex.SocketErrorCode, sex.Message));
                    handler.stateObject.message = null;
                    handler.stateObject.pendingBuffer = null;
                    handler.Close();
                }
                else
                {
                    Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", sex));
                    handler.stateObject.message = null;
                    handler.stateObject.pendingBuffer = null;
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception {0}. Connection will be closed", ex));
                handler.stateObject.message = null;
                handler.stateObject.pendingBuffer = null;
                handler.Close();
            }
        }