Beispiel #1
0
        /// <summary> Writes all queued <see cref="Packet"/> objects in the <see cref="sendPackets"/> queue to the network. </summary>
        private void WriteSubWork()
        {
            while (sendPackets.Count > 0)
            {
                Tuple <Packet, object> packetWithObject = null;
                if (!sendPackets.TryDequeue(out packetWithObject))
                {
                    continue;
                }

                Packet packet = packetWithObject.Item1;

                //Insert the ID into the packet if it is an request packet.
                if (packet.GetType().IsSubclassOf(typeof(RequestPacket)) && packetWithObject.Item2 != null)
                {
                    packet.ID = packetHandlerMap[requestResponseMap[packet.GetType()], packetWithObject.Item2];
                }

                //Prepare some data in the packet.
                packet.BeforeSend();

                /*              Packet structure:
                 *              1. [16bits] packet type
                 *              2. [32bits] packet length 包内容长度,不包括1和2
                 *              3. [xxbits] packet data                 */

                //if (packet.ID)
                //{

                //}
                byte[] packetData   = packetConverter.GetBytes(packet);
                byte[] packetLength = BitConverter.GetBytes(packetData.Length);                    //包 内容的长度
                byte[] packetByte   = new byte[2 + packetLength.Length + packetData.Length];       //总长度byte表示,包括包头,包长,包内容

                packetByte[0] = (byte)(typeByte[packet.GetType()]);                                //pack type
                packetByte[1] = (byte)(typeByte[packet.GetType()] >> 8);                           //pack type
                Array.Copy(packetLength, 0, packetByte, 2, packetLength.Length);                   //包长度 控制字符
                Array.Copy(packetData, 0, packetByte, 2 + packetLength.Length, packetData.Length); //包内容
                WriteBytes(packetByte);

                Logger.LogOutgoingPacket(packetData, packet);
            }
        }
Beispiel #2
0
 internal static byte[] GetBytesWrap <T>(this IPacketConverter <T> converter, T value)
 {
     try
     {
         var buf = converter.GetBytes(value);
         if (buf == null)
         {
             buf = s_empty_bytes;
         }
         var len = converter.Length;
         if (len > 0 && len != buf.Length)
         {
             throw PacketException.ConvertMismatch(len);
         }
         return(buf);
     }
     catch (Exception ex) when(PacketException.WrapFilter(ex))
     {
         throw PacketException.ConvertError(ex);
     }
 }