Ejemplo n.º 1
0
        public static ServersPool CreateServersPool(ServerListeningMode mode, IProtoProvider protocol)
        {
            if ((mode & ServerListeningMode.MultiTransport) == ServerListeningMode.MultiTransport)
            {
                if ((mode & ServerListeningMode.MultiTransportSecure) == ServerListeningMode.MultiTransportSecure)
                {
                    return(new ServersPool(new SecureTcpServer(protocol), new SecureUdpServer(protocol)));
                }

                return(new ServersPool(new TcpServer(protocol), new UdpServer(protocol)));
            }

            if ((mode & ServerListeningMode.Tcp) == ServerListeningMode.Tcp)
            {
                if ((mode & ServerListeningMode.TcpSecure) == ServerListeningMode.TcpSecure)
                {
                    return(new ServersPool(new SecureTcpServer(protocol)));
                }

                return(new ServersPool(new TcpServer(protocol)));
            }

            if ((mode & ServerListeningMode.Udp) == ServerListeningMode.Udp)
            {
                if ((mode & ServerListeningMode.UdpSecure) == ServerListeningMode.UdpSecure)
                {
                    return(new ServersPool(new SecureUdpServer(protocol)));
                }

                return(new ServersPool(new UdpServer(protocol)));
            }

            throw new ArgumentException($"Invalid server mode for factory!");
        }
Ejemplo n.º 2
0
 public Connection(IProtoProvider provider, Func <Stream, Type, int, object> deserializeMessageAction = null)
 {
     m_lockState = new object();
     State       = ConnectionState.None;
     Provider    = provider;
     m_messageDeserializeAction = deserializeMessageAction;
     ConnSocket = null;
 }
Ejemplo n.º 3
0
        public TcpServer(IProtoProvider protocol)
        {
            if (protocol == null)
            {
                throw new ArgumentNullException();
            }

            m_ProtocolProvider  = protocol;
            m_ListeningTasks    = new List <Task>();
            m_ReceivingTasks    = new List <Task>();
            m_CurrentProcessor  = new NetworkProcessor();
            m_ActiveConnections = new Dictionary <Guid, NetworkConnection>();

            RegisterProcessors();
        }
Ejemplo n.º 4
0
        // Token: 0x06006B14 RID: 27412 RVA: 0x001E0AF0 File Offset: 0x001DECF0
        public static ArraySegment <byte> EncodeMessage(object vMsg, IProtoProvider protoProvider)
        {
            byte[]       array        = new byte[65536];
            MemoryStream memoryStream = new MemoryStream(array);
            BinaryWriter binaryWriter = new BinaryWriter(memoryStream);

            binaryWriter.Write(0);
            binaryWriter.Write(0);
            RuntimeTypeModel.Default.Serialize(memoryStream, vMsg, null);
            bool   flag = memoryStream.Position - 4L >= 400L;
            ushort num;

            if (flag)
            {
                using (MemoryStream memoryStream2 = new MemoryStream(memoryStream.ToArray(), 4, (int)memoryStream.Position - 4))
                {
                    byte[] array2 = QuickLZ.compress(memoryStream2.ToArray(), 3);
                    memoryStream.Seek(4L, SeekOrigin.Begin);
                    memoryStream.Write(array2, 0, array2.Length);
                }
                num = (ushort)memoryStream.Position;
                binaryWriter.Seek(0, SeekOrigin.Begin);
                binaryWriter.Write(num);
                ushort num2 = (ushort)protoProvider.GetIdByType(vMsg.GetType());
                num2 |= 32768;
                binaryWriter.Write(num2);
            }
            else
            {
                num = (ushort)memoryStream.Position;
                binaryWriter.Seek(0, SeekOrigin.Begin);
                binaryWriter.Write(num);
                ushort num3 = (ushort)protoProvider.GetIdByType(vMsg.GetType());
                num3 &= 32767;
                binaryWriter.Write(num3);
            }
            return(new ArraySegment <byte>(array, 0, (int)num));
        }
Ejemplo n.º 5
0
 public SecureTcpServer(IProtoProvider protocol)
 {
 }
Ejemplo n.º 6
0
 // Token: 0x06006AEF RID: 27375 RVA: 0x001DFCC0 File Offset: 0x001DDEC0
 public Connection(IProtoProvider provider, Func <Stream, Type, int, object> deserializeMessageAction = null)
 {
     this.State      = ConnectionState.None;
     this.m_provider = provider;
     this.m_messageDeserializeAction = deserializeMessageAction;
 }
Ejemplo n.º 7
0
        // Token: 0x06006B13 RID: 27411 RVA: 0x001E0934 File Offset: 0x001DEB34
        public static object DecodeMessage(MessageBlock recvBuffer, IProtoProvider protoProvider, out int msgId, Func <Stream, Type, int, object> deserializeMessageAction = null)
        {
            int num = 4;

            msgId = 0;
            if (recvBuffer.Length < num)
            {
                return(null);
            }
            ushort num2 = recvBuffer.ReadUInt16();

            if ((int)num2 < num)
            {
                throw new ProtoException(string.Format("Hack stream, TotalLength={0}", num2));
            }
            int num3 = (int)num2 - num;

            if (recvBuffer.Length < num3 + 2)
            {
                recvBuffer.ReadPtr(-2);
                return(null);
            }
            ushort num4 = recvBuffer.ReadUInt16();
            bool   flag = num4 >> 15 == 1;
            ushort num5 = num4 & 32767;

            msgId = (int)num5;
            Type   typeById = protoProvider.GetTypeById((int)num5);
            object result;

            try
            {
                if (flag)
                {
                    using (MemoryStream readStream = recvBuffer.GetReadStream(num3))
                    {
                        byte[] array = QuickLZ.decompress(readStream.ToArray());
                        int    count = array.Length;
                        using (MemoryStream memoryStream = new MemoryStream(array, 0, count))
                        {
                            if (deserializeMessageAction != null)
                            {
                                result = deserializeMessageAction(memoryStream, typeById, msgId);
                            }
                            else
                            {
                                result = RuntimeTypeModel.Default.Deserialize(memoryStream, null, typeById, null);
                            }
                        }
                    }
                }
                else
                {
                    using (MemoryStream readStream2 = recvBuffer.GetReadStream(num3))
                    {
                        if (deserializeMessageAction != null)
                        {
                            result = deserializeMessageAction(readStream2, typeById, msgId);
                        }
                        else
                        {
                            result = RuntimeTypeModel.Default.Deserialize(readStream2, null, typeById, null);
                        }
                    }
                }
            }
            catch (Exception innerException)
            {
                throw new Exception(string.Format("msgId={0}, isCompressed={1} pakBodyLength={2}", msgId, flag, num3), innerException);
            }
            return(result);
        }
Ejemplo n.º 8
0
 public UdpServer(IProtoProvider protocol)
 {
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Decodes the message.
        /// </summary>
        /// <returns>The message.</returns>
        /// <param name="dataBlock">Data block.</param>
        /// <param name="dataOffset">Data offset.</param>
        /// <param name="dataLen">Data length.</param>
        /// <param name="newMsg">New message.</param>
        /// <returns>
        ///     != null     : A protocol message
        ///     == null     : No full message exist
        ///     Exception   : ProtoException to indicate HACK stream
        /// </returns>
        public static Object DecodeMessage(MessageBlock rCache, IProtoProvider protoProvider, out int msgId)
        {
            msgId = 0;
            // get the message head's length
            int headLength = sizeof(ushort) * 2;

            // Not enough data for header
            if (rCache.Length < headLength)
            {
                //Debug.WriteLine(String.Format("DecodeMessage Not enough data for header. rCache.Length={0} < headLength={1}", rCache.Length, headLength));
                return(null);
            }

            // get message length
            ushort pakFullLength = rCache.ReadUInt16();

            // Bad stream
            if (pakFullLength < headLength)
            {
                throw new ProtoException(string.Format("Hack stream, TotalLength={0}", pakFullLength));
            }

            int pakBodyLength = pakFullLength - headLength;

            //Debug.WriteLine(String.Format("DecodeMessage Before rCache.Length={0} pakBodyLength={1} ", rCache.Length, pakBodyLength));

            // Not enough data for body
            // ע��������Ҫ���Ǻ���һ����ͷ�ij���
            if (rCache.Length < pakBodyLength + sizeof(ushort))
            {
                // Move read ptr to back
                // �˴�ֻ������UInt16���ȵ����ݣ����Իع���Ҫһ�£�����ʹ��headLength
                rCache.ReadPtr(-(sizeof(ushort)));
                //Debug.WriteLine(String.Format("DecodeMessage Not enough data for body rCache.Length={0} < pakBodyLength={1}", rCache.Length, pakBodyLength));
                return(null);
            }

            // get message id field
            ushort pakMessageIdField = rCache.ReadUInt16();
            // get compressed tag
            bool isCompressed = pakMessageIdField >> (sizeof(ushort) * 8 - 1) == 1;

            // get the protocol id
            msgId = (ushort)(pakMessageIdField & 0x7FFF);

            // deserialize message, we should decompress message body data if needed
            Type pakType = protoProvider.GetTypeById(msgId);
            // Use ProtoBuf to deserialize message
            object ccMsg = Activator.CreateInstance(pakType);

            //Debug.WriteLine(String.Format("DecodeMessage msgId={0} pakBodyLength={1} isCompressed={2} pakType={3}", msgId, pakBodyLength, isCompressed, pakType.ToString()));
            try
            {
                using (MemoryStream readStream = rCache.GetStream(pakBodyLength))
                {
                    //����Ϣ���л����������ṩ�����л����������л��ͷ����л�
                    //Debug.WriteLine(String.Format("DecodeMessage readStream={0}", printByteArray(readStream.ToArray())));
                    //RuntimeTypeModel.Default.Deserialize(readStream, ccMsg, pakType);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("msgId={0}, isCompressed={1} pakBodyLength={2}",
                                                  msgId, isCompressed, pakBodyLength), ex);
            }

            //Debug.WriteLine(String.Format("DecodeMessage rCacheInfo Length={0} WrPtr={1} RdPtr={2}", rCache.Length, rCache.WrPtr, rCache.RdPtr));
            return(ccMsg);
        }
Ejemplo n.º 10
0
        ///// <summary>
        ///// ��ӡbyte����
        ///// </summary>
        ///// <param name="array"></param>
        ///// <returns></returns>
        //private static string printByteArray(byte[] array)
        //{
        //    if (array == null || array.Length == 0) return string.Empty;

        //    System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //    foreach (var c in array)
        //    {
        //        sb.AppendFormat("{0} ", c);
        //    }
        //    return sb.ToString();
        //}

        /// <summary>
        /// Encodes the message through protobuff, the message's format is : messageSize(UInt16)-ProtocolId(UInt16, including the compressTag and the protocolId value)-ProtocolData
        /// </summary>
        /// <returns>The ecoded message stream.</returns>
        /// <param name="vMsg">The message.</param>
        public static ArraySegment <byte> EncodeMessage(Object vMsg, IProtoProvider protoProvider)
        {
            byte[]       fullBuf  = new byte[(Int32)ProtoConst.MAX_PACKAGE_LENGTH];
            MemoryStream wrStream = new MemoryStream(fullBuf);
            BinaryWriter bnWriter = new BinaryWriter(wrStream);

            // get the message head's length
            int headLength = sizeof(ushort) * 2;

            // Total length, placehold only now
            bnWriter.Write((ushort)0);
            // Message ID, placehold only now
            bnWriter.Write((ushort)0);
            // write message body data to stream
            //RuntimeTypeModel.Default.Serialize(wrStream, vMsg);

            // if the length of message body data is longer than a specific value, then we need compress the message body data
            bool   needCompress = wrStream.Position - headLength >= ProtoConst.ZIP_BUFFER_MIN_LENGTH;
            ushort fullLength   = 0;

            if (needCompress)
            {
                // allocate the buffer for keeping compressed data
                //using (MemoryStream zipMs = new MemoryStream())
                //{
                //    using (GZipStream compressionStream = new GZipStream(zipMs, CompressionMode.Compress))
                //    {
                //        compressionStream.Write(wrStream.ToArray(), headLength, (int)wrStream.Position - headLength);
                //    }
                //    wrStream.Seek(headLength, SeekOrigin.Begin);
                //    wrStream.Write(zipMs.ToArray(), 0, zipMs.ToArray().Length);
                //}

                using (MemoryStream zipMs = new MemoryStream(wrStream.ToArray(), headLength, (int)wrStream.Position - headLength))
                {
                    //var compressedByte = QuickLZSharp.QuickLZ.compress(zipMs.ToArray(), 3);
                    //var compressedByte;

                    //wrStream.Seek(headLength, SeekOrigin.Begin);
                    //wrStream.Write(compressedByte, 0, compressedByte.Length);
                }

                // Rewrite the message length
                fullLength = (ushort)wrStream.Position;
                bnWriter.Seek(0, SeekOrigin.Begin);
                bnWriter.Write(fullLength);
                // Rewrite the message ID info
                ushort protocolId = (ushort)(protoProvider.GetIdByType(vMsg.GetType()));
                protocolId = (ushort)(protocolId | 0x8000);
                bnWriter.Write(protocolId);
            }
            else
            {
                // Rewrite the message length
                fullLength = (ushort)wrStream.Position;
                bnWriter.Seek(0, SeekOrigin.Begin);
                bnWriter.Write(fullLength);
                // Rewrite the message ID info
                ushort protocolId = (ushort)(protoProvider.GetIdByType(vMsg.GetType()));
                protocolId = (ushort)(protocolId & 0x7FFF);
                bnWriter.Write(protocolId);
            }

            return
                (new ArraySegment <byte>(fullBuf, 0, fullLength));
        }