public void Initialize(IAppSession appSession)
        {
            this.AppSession = appSession as AppSession;

            SendingQueue queue;

            if (m_SendingQueuePool.TryGet(out queue))
            {
                m_SendingQueue = queue;
                queue.StartEnqueue();
            }

            SocketAsyncProxy.Initialize(this);

            //Initialize SocketAsyncEventArgs for sending
            m_SocketEventArgSend            = new SocketAsyncEventArgs();
            m_SocketEventArgSend.Completed += new EventHandler <SocketAsyncEventArgs>(OnSendingCompleted);
        }
 private void Send(SendingQueue queue)
 {
     SendAsync(queue);
 }
 protected void OnSendError(SendingQueue queue, CloseReason closeReason)
 {
     queue.Clear();
     m_SendingQueuePool.Push(queue);
     OnSendEnd(closeReason, true);
 }
        private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
        {
            if (initial)
            {
                if (!TryAddStateFlag(SocketState.InSending))
                {
                    return;
                }

                var currentQueue = m_SendingQueue;

                if (currentQueue != queue || sendingTrackID != currentQueue.TrackID)
                {
                    //Has been sent
                    OnSendEnd();
                    return;
                }
            }

            Socket client;

            if (IsInClosingOrClosed && TryValidateClosedBySocket(out client))
            {
                OnSendEnd();
                return;
            }

            SendingQueue newQueue;

            if (!m_SendingQueuePool.TryGet(out newQueue))
            {
                OnSendEnd(CloseReason.InternalError, true);
                AppSession.Logger.Error("There is no enougth sending queue can be used.");
                return;
            }

            var oldQueue = Interlocked.CompareExchange(ref m_SendingQueue, newQueue, queue);

            if (!ReferenceEquals(oldQueue, queue))
            {
                if (newQueue != null)
                {
                    m_SendingQueuePool.Push(newQueue);
                }

                if (IsInClosingOrClosed)
                {
                    OnSendEnd();
                }
                else
                {
                    OnSendEnd(CloseReason.InternalError, true);
                    AppSession.Logger.Error("Failed to switch the sending queue.");
                }

                return;
            }

            //Start to allow enqueue
            newQueue.StartEnqueue();
            queue.StopEnqueue();

            if (queue.Count == 0)
            {
                m_SendingQueuePool.Push(queue);
                OnSendEnd(CloseReason.InternalError, true);
                AppSession.Logger.Error("There is no data to be sent in the queue.");
                return;
            }

            Send(queue);
        }