Пример #1
0
        /// <summary>
        /// Sends the specified data to the client.
        /// </summary>
        /// <param name="data">The data to send.</param>
        public void Send(byte[] data)
        {
            PacketState state = null;

            lock ( mLock )
            {
                // TODO: Make this log to file (and conditional).
                ConsoleHelper.WriteHex("Sent (" + data.Length.ToString() + " bytes):", data, 0, data.Length, ConsoleColor.DarkBlue);

                mOutgoingData.AddRange(data);
                if (!mSending)
                {
                    state = new PacketState
                    {
                        Data   = mOutgoingData.ToArray(),
                        Offset = 0
                    };
                    mOutgoingData.Clear();

                    mSocket.BeginSend(state.Data, 0, state.Data.Length, SocketFlags.None, mSendCallback, state);

                    mSending = true;
                }
                else
                {
                    return;
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Sends outgoing data to the client or stops sending of there is no outgoing data available.
        /// </summary>
        /// <param name="result"></param>
        void OnDataSent(IAsyncResult result)
        {
            try
            {
                PacketState state = (PacketState)result.AsyncState;
                int         sent  = mSocket.EndSend(result);
                state.Offset += sent;

                // Make sure everything is being sent.
                int bytesLeft = (state.Data.Length - sent);
                if (bytesLeft > 0)
                {
                    state.Offset += sent;

                    mSocket.BeginSend(state.Data, state.Offset, bytesLeft, SocketFlags.None, mSendCallback, state);

                    return;
                }

                // Begin sending the next packet or stop sending if theres no outgoing data available.
                lock ( mLock )
                {
                    if (mOutgoingData.Count == 0)
                    {
                        mSending = false;
                    }
                    else
                    {
                        state.Data   = mOutgoingData.ToArray();
                        state.Offset = 0;
                        mOutgoingData.Clear();

                        mSocket.BeginSend(state.Data, 0, state.Data.Length, SocketFlags.None, mSendCallback, state);
                    }
                }
            }
            catch { Close(); }
        }