예제 #1
0
 public void Send(IPacket packet)
 {
     try
     {
         byte[]     data       = packet.GetData();
         HeadStream headStream = new HeadStream();
         headStream.Write(BitConverter.GetBytes(data.Length));
         headStream.Close();
         //Console.WriteLine("准备发送的包长度:" + data.Length);
         List <byte> sendData = new List <byte>();
         sendData.AddRange(PREAMBLE);
         sendData.AddRange(data);
         if (IsListen && !MultiSocket)
         {
             clientSocket.Send(headStream.GetBuffer());
             clientSocket.Send(sendData.ToArray());
         }
         else
         {
             socket.Send(headStream.GetBuffer());
             socket.Send(sendData.ToArray());
         }
     }
     catch (Exception)
     {
         Disconnect();
     }
 }
예제 #2
0
        /// <summary>
        /// Socket层面上接收包,接收到包放进包缓冲池
        /// </summary>
        protected void SocketReceive()
        {
            try
            {
                while (true)
                {
                    //socket.ReceiveTimeout = 3000;
                    HeadStream headStream   = ReceiveHeadStream(HEAD_STREAM_SIZE);//头部有256字节的信息,提取有用部分到headStream
                    int        packetLength = BitConverter.ToInt32(headStream.Read(sizeof(int)), 0);

                    headStream.Close();
                    Packet packet = Receive(packetLength);
                    packet.transport = this;//给包贴上接收者的标签
                    if (packet == null)
                    {
                        return;
                    }
                    packetPool.Add(packet);
                    UpdateReceive();
                }
            }
            catch (Exception)
            {
                Disconnect();
            }
        }