Пример #1
0
        protected void sendDataPacket(SocketAsyncEventArgs sendArgs)
        {
            SendUserToken token = (SendUserToken)sendArgs.UserToken;

            if (token.DataToSend == null)
            {
                IDataPacket dp         = token.DataPacket;
                byte[]      dataBuffer = dp.Serialize();

                IDataPacketHeader dph = _dataProcessor.CreateDataPacketHeader();
                dph.DataPacketSize = dataBuffer.Length;

                byte[] headerBuffer = dph.Serialize();
                int    nSize        = dataBuffer.Length + headerBuffer.Length;
                byte[] packetBuffer = new byte[nSize];
                Buffer.BlockCopy(headerBuffer, 0, packetBuffer, 0, headerBuffer.Length);
                Buffer.BlockCopy(dataBuffer, 0, packetBuffer, headerBuffer.Length, dataBuffer.Length);
                token.DataToSend           = packetBuffer;
                token.SentDataOffset       = 0;
                token.ProcessedDataRemains = packetBuffer.Length;
            }
            if (token.ProcessedDataRemains <= nBufferSize && token.SentDataOffset == 0) //data packet fully fit in send buffer
            {
                Buffer.BlockCopy(token.DataToSend, 0, sendArgs.Buffer, sendArgs.Offset, token.DataToSend.Length);
                token.Reset();
            }
            else
            {// need to separate data packet into several buffers
                int nLength = token.ProcessedDataRemains <= nBufferSize ? token.ProcessedDataRemains : nBufferSize;
                Buffer.BlockCopy(token.DataToSend, token.SentDataOffset, sendArgs.Buffer,
                                 sendArgs.Offset, nLength);

                token.SentDataOffset       += nLength;
                token.ProcessedDataRemains -= nLength;
                if (token.ProcessedDataRemains == 0)
                {
                    token.Reset();
                }
            }
            byte[] testByte2 = new byte[nBufferSize];
            Buffer.BlockCopy(sendArgs.Buffer, sendArgs.Offset, testByte2, 0, nBufferSize);
            string strOut = Encoding.UTF8.GetString(testByte2);

            Debug.WriteLine("Send = {0}", strOut);

            if (!sendArgs.AcceptSocket.SendAsync(sendArgs))
            {
                sendArgs_Completed(sendArgs.AcceptSocket, sendArgs);
            }
        }