Ejemplo n.º 1
0
 public ModifiableProtocol(IPacketEncryptor encryptor=null, IPacketDecryptor decryptor=null, IPacketEncoder encoder=null, IPacketDecoder decoder=null)
 {
     _encryptor = encryptor;
     _decryptor = decryptor;
     _encoder = encoder;
     _decoder = decoder;
 }
Ejemplo n.º 2
0
        private void SendUpdateStatePacket(UpdateState state, User user, IPAddress brdIp)
        {
            UdpPacket packet = new UdpPacket();

            packet.Address = user.Address;
            packet.Port    = user.Port;
            packet.ToMAC   = "";
            packet.FromMAC = user.ID;
            packet.Command = UdpPacket.CMD_STATE;

            UdpPacketUserStateExtend entryExtend = new UdpPacketUserStateExtend();

            entryExtend.User        = user;
            entryExtend.UpdateState = state;

            packet.Extend = entryExtend;

            UdpPacket packetWrap = new UdpPacket();

            packetWrap.Address = brdIp;
            packetWrap.Port    = this.Port;
            packetWrap.ToMAC   = "";
            packetWrap.FromMAC = this.MAC;
            packetWrap.Command = UdpPacket.CMD_RETRANSMIT;

            IPacketEncoder encoder = PacketEncoderFactory.CreateEncoder(packet);
            EncodeResult   result  = encoder.Encode();

            UdpPacketRetransExtend extend = new UdpPacketRetransExtend(result.Fragments[0]);

            packetWrap.Extend = extend;

            _client.Send(packetWrap);
        }
Ejemplo n.º 3
0
        internal virtual IPacketEncoder CreateIPacketEncoder()
        {
            // TODO: 实例化相应的具体类。
            IPacketEncoder target = null;

            return(target);
        }
Ejemplo n.º 4
0
 public static ChannelPipe CreateChannelPipe(IPacketEncoder encoder, IPacketDecoder decoder, IChannelHandler handler)
 {
     var pipe = new ChannelPipe();
     pipe.SetCreateChannelAction((channel) =>
     {
         channel.SetConfig("encoder", encoder);
         channel.SetConfig("decoder", decoder);
         channel.SetConfig("handler", handler);
     });
     return pipe;
 }
Ejemplo n.º 5
0
        public void PacketEncoderTest()
        {
            ClientSocketManager clientSocket = null;                                    // TODO: 初始化为适当的值
            MessagePump         messagePump  = null;                                    // TODO: 初始化为适当的值
            NetState            target       = new NetState(clientSocket, messagePump); // TODO: 初始化为适当的值
            IPacketEncoder      expected     = null;                                    // TODO: 初始化为适当的值
            IPacketEncoder      actual;

            target.PacketEncoder = expected;
            actual = target.PacketEncoder;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Ejemplo n.º 6
0
        public void DecodeIncomingPacketTest()
        {
            IPacketEncoder target       = CreateIPacketEncoder(); // TODO: 初始化为适当的值
            NetState       netStateFrom = null;                   // TODO: 初始化为适当的值

            byte[] byteBuffer         = null;                     // TODO: 初始化为适当的值
            byte[] byteBufferExpected = null;                     // TODO: 初始化为适当的值
            long   iLength            = 0;                        // TODO: 初始化为适当的值
            long   iLengthExpected    = 0;                        // TODO: 初始化为适当的值

            target.DecodeIncomingPacket(netStateFrom, ref byteBuffer, ref iLength);
            Assert.AreEqual(byteBufferExpected, byteBuffer);
            Assert.AreEqual(iLengthExpected, iLength);
            Assert.Inconclusive("无法验证不返回值的方法。");
        }
Ejemplo n.º 7
0
        public Client(IPacketEncoder encoder, IPacketDecoder decoder)
        {
            // Properties를 생성합니다. Properties는 Netronics의 각종 설정을 의미합니다.
            var properties = Properties.CreateProperties(new IPEndPoint(IPAddress.Loopback, 9999), // 서버의 아이피와 포트를 설정합니다.
                                                         new ChannelPipe().SetCreateChannelAction(channel =>
                                                         {
                                                             channel.SetConfig("encoder", encoder); // 해당 Channel의 Packet Encoder을 설정합니다.
                                                             channel.SetConfig("decoder", decoder); // 해당 Channel의 Packet Decoder을 설정합니다.
                                                             channel.SetConfig("handler", this); // 해당 Channel의 Handler을 설정합니다.

                                                             //기본적인 switch는 같은 채널은 같은 스래드에서 처리되기때문에 메시지 처리가 같은 스레드에서 일어날것.
                                                         }));

            netronics = new global::Netronics.Client(properties); // 위에서 만든 Properties를 바탕으로 Netronics 객체를 생성합니다.
            netronics.Start(); // 서버를 가동합니다.
        }
Ejemplo n.º 8
0
        public Server(IPacketEncoder encoder, IPacketDecoder decoder)
        {
            // Properties를 생성합니다. Properties는 Netronics의 각종 설정을 의미합니다.
            var properties = Properties.CreateProperties(new IPEndPoint(IPAddress.Any, 9999), // 클라이언트를 받을 아이피와 포트를 설정합니다.
                                                         new ChannelPipe().SetCreateChannelAction(channel => // 각 클라이언트가 접속하면 Channel을 생성하는 과정이 시작되는데 옵션을 아래와 같이 넣을 수 있습니다.
                                                         {
                                                             Console.WriteLine("전달하기 전 Channel의 설정");
                                                             channel.SetConfig("encoder", encoder); // 해당 Channel의 Packet Encoder을 설정합니다.
                                                             channel.SetConfig("decoder", decoder); // 해당 Channel의 Packet Decoder을 설정합니다.
                                                             channel.SetConfig("handler", this); // 해당 Channel의 Handler을 설정합니다.

                                                             channel.SetConfig("switch", new RandemSwitch()); //랜덤으로 전달되는지 확인 ReceiveSwitch 테스트

                                                             Console.WriteLine("Channel을 Netronics로 전달");
                                                         }));

            netronics = new Netronics(properties); // 위에서 만든 Properties를 바탕으로 Netronics 객체를 생성합니다.
            netronics.Start(); // 서버를 가동합니다.
        }
Ejemplo n.º 9
0
 public PacketOverrideRegistryEncoder(IPacketEncoder successor)
 {
     _Successor = successor;
 }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="netState"></param>
        internal static void WorldProcessReceive(object sender, NetStateEventArgs eventArgs)
        {
            LOGs.WriteLine(LogMessageType.MSG_HACK, "World_ProcessReceive...... 0 = {0}", eventArgs.NetState.ReceiveBuffer.Length);

            if (eventArgs.NetState == null)
            {
                Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - eventArgs.NetState == null error!");
                return;
            }

            ReceiveQueue receiveQueueBuffer = eventArgs.NetState.ReceiveBuffer;

            if (receiveQueueBuffer == null)
            {
                Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - receiveQueueBuffer == null error!");
                return;
            }

            WorldExtendData extendData = eventArgs.NetState.GetComponent <WorldExtendData>(WorldExtendData.COMPONENT_ID);

            if (extendData == null)
            {
                Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - extendData == null error!");
                return;
            }

            if (receiveQueueBuffer.Length < extendData.ProcessReceiveData.Remaining)
            {
                                                                                       // 等待数据包的完整(Remaining 默认的大小为WORLD_HEAD_SIZE)
                return;
            }

            long iReceiveBufferLength = receiveQueueBuffer.Length; // 隔段时间就会有数据过来,所以可以不用锁定的,锁定了也没用,很难保证多线程中处理了所有的数据(指 Length)

            while (iReceiveBufferLength >= extendData.ProcessReceiveData.Remaining)
            {
                if (extendData.ProcessReceiveData.PacketBuffer == null)   // 如果空 代表是需要获取新的数据包和包头(Remaining == WORLD_HEAD_SIZE)
                {
                    // 获取空数据
                    byte[] packetBuffer = s_ProcessorBuffers.AcquireBuffer();

                    // 获取数据包头的内容
                    long iReturnPacketHeadSize = receiveQueueBuffer.Dequeue(ref packetBuffer, 0, WORLD_HEAD_SIZE);

                    // 获取的数据不相同
                    if (iReturnPacketHeadSize != WORLD_HEAD_SIZE)
                    {
                        Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - iReturnPacketHeadSize != WORLD_HEAD_SIZE error!");

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    IPacketEncoder packetEncoder = eventArgs.NetState.PacketEncoder as IPacketEncoder;
                    if (packetEncoder == null)
                    {
                        Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - packetEncoder == null error!");

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    // 解密数据包头
                    long iClientPacketHeader = WORLD_HEAD_SIZE;
                    packetEncoder.DecodeIncomingPacket(eventArgs.NetState, ref packetBuffer, ref iClientPacketHeader);

                    // 给出数据信息头
                    WOWClientPacketHeader clientPacketHeader = WOWClientPacketHeader.GetClientPacketHeader(packetBuffer);

                    int iRemaining = clientPacketHeader.PacketSize - 4; // -4 是代表剩余的数据包大小(为什么不是减6呢?)
                    if (receiveQueueBuffer.Length < iRemaining)
                    {
                                                                  // 等待数据包的完整
                        {
                            extendData.ProcessReceiveData.PacketBuffer = packetBuffer;
                            extendData.ProcessReceiveData.Remaining    = (uint)iRemaining;

                            return;
                        }
                    }

                    // 获取信息包数据的剩余内容
                    long iReturnPacketSize = receiveQueueBuffer.Dequeue(ref packetBuffer, WORLD_HEAD_SIZE, iRemaining /*获取剩余数据包大小的字节数*/);

                    // 获取的数据不相同
                    if (iReturnPacketSize != iRemaining)
                    {
                        Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - iReturnPacketSize != iRemaining error!");

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    // 获取包的全部长度
                    long iPacketFullLength = iRemaining + WORLD_HEAD_SIZE;

                    // 读取的数据包
                    PacketReader packetReader = new PacketReader(packetBuffer, iPacketFullLength, WORLD_HEAD_SIZE /*包的ID大小-4个字节、长度大小-2个字节, 6个字节跳过*/);


                    //////////////////////////////////////////////////////////////////////////
                    // 输出信息包的日志
                    //////////////////////////////////////////////////////////////////////////
                    ProcessNet.LogServerPack(packetBuffer, iPacketFullLength, "World_In_Packets.log", eventArgs.NetState.ToString(), clientPacketHeader.PacketID, WordOpCodeName.GetWordOpCodeName(clientPacketHeader.PacketID));
                    //////////////////////////////////////////////////////////////////////////


                    // 获取处理数据包的实例
                    PacketHandler packetHandler = ProcessServer.WorldPacketHandlers.GetHandler(clientPacketHeader.PacketID);
                    if (packetHandler == null)   // 说明还没有解开当前的数据包内容
                    {
                        //////////////////////////////////////////////////////////////////////////
                        // 输出未知信息包的日志
                        //////////////////////////////////////////////////////////////////////////
                        ProcessNet.LogServerPack(packetBuffer, iPacketFullLength, "World_In_Unknown_Packets.log", eventArgs.NetState.ToString(), clientPacketHeader.PacketID, WordOpCodeName.GetWordOpCodeName(clientPacketHeader.PacketID));
                        //////////////////////////////////////////////////////////////////////////

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        // 获取剩下的数据长度
                        iReceiveBufferLength = receiveQueueBuffer.Length;

                        continue;
                    }

                    // 当前需处理的数据包的大小
                    long iPacketHandlerLength = packetHandler.Length;
                    if (iPacketHandlerLength > iPacketFullLength)   // 包需求的数据大小大于得到的数据大小
                    {
                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    // 处理数据
                    packetHandler.OnReceive(eventArgs.NetState, packetReader);

                    // 返回内存池
                    s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                    // 获取剩下的数据长度
                    iReceiveBufferLength = receiveQueueBuffer.Length;
                }
                else    //已有数据包头获取剩余数据
                {
                    byte[] packetBuffer = extendData.ProcessReceiveData.PacketBuffer;

                    // 获取信息包数据的剩余内容
                    long iReturnPacketSize = receiveQueueBuffer.Dequeue(ref packetBuffer, WORLD_HEAD_SIZE, extendData.ProcessReceiveData.Remaining /*获取剩余数据包大小的字节数*/);

                    // 获取的数据不相同
                    if (iReturnPacketSize != extendData.ProcessReceiveData.Remaining)
                    {
                        Debug.WriteLine("ProcessNet.World_ProcessReceive(...) - iReturnPacketSize != Remaining error!");

                        // 恢复原始数据状态
                        extendData.ProcessReceiveData.PacketBuffer = null;
                        extendData.ProcessReceiveData.Remaining    = WORLD_HEAD_SIZE;

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    // 获取包的全部长度
                    long iPacketFullLength = extendData.ProcessReceiveData.Remaining + WORLD_HEAD_SIZE;

                    // 读取的数据包
                    PacketReader packetReader = new PacketReader(extendData.ProcessReceiveData.PacketBuffer, iPacketFullLength, WORLD_HEAD_SIZE /*包的ID大小-4个字节、长度大小-2个字节, 6个字节跳过*/);

                    // 给出数据信息头
                    WOWClientPacketHeader clientPacketHeader = WOWClientPacketHeader.GetClientPacketHeader(extendData.ProcessReceiveData.PacketBuffer);


                    //////////////////////////////////////////////////////////////////////////
                    // 输出信息包的日志
                    //////////////////////////////////////////////////////////////////////////
                    ProcessNet.LogServerPack(packetBuffer, iPacketFullLength, "World_In_Packets.log", eventArgs.NetState.ToString(), clientPacketHeader.PacketID, WordOpCodeName.GetWordOpCodeName(clientPacketHeader.PacketID));
                    //////////////////////////////////////////////////////////////////////////


                    // 获取处理数据包的实例
                    PacketHandler packetHandler = ProcessServer.WorldPacketHandlers.GetHandler(clientPacketHeader.PacketID);
                    if (packetHandler == null)   // 说明还没有解开当前的数据包内容
                    {
                        //////////////////////////////////////////////////////////////////////////
                        // 输出未知信息包的日志
                        //////////////////////////////////////////////////////////////////////////
                        ProcessNet.LogServerPack(packetBuffer, iPacketFullLength, "World_In_Unknown_Packets.log", eventArgs.NetState.ToString(), clientPacketHeader.PacketID, WordOpCodeName.GetWordOpCodeName(clientPacketHeader.PacketID));
                        //////////////////////////////////////////////////////////////////////////

                        // 恢复原始数据状态
                        extendData.ProcessReceiveData.PacketBuffer = null;
                        extendData.ProcessReceiveData.Remaining    = WORLD_HEAD_SIZE;

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        // 获取剩下的数据长度
                        iReceiveBufferLength = receiveQueueBuffer.Length;

                        continue;
                    }

                    // 当前需处理的数据包的大小
                    long iPacketHandlerLength = packetHandler.Length;
                    if (iPacketHandlerLength > iPacketFullLength)   // 包需求的数据大小大于得到的数据大小
                    {
                        // 恢复原始数据状态
                        extendData.ProcessReceiveData.PacketBuffer = null;
                        extendData.ProcessReceiveData.Remaining    = WORLD_HEAD_SIZE;

                        // 返回内存池
                        s_ProcessorBuffers.ReleaseBuffer(packetBuffer);

                        eventArgs.NetState.Dispose(); // 断开
                        return;
                    }

                    // 处理数据
                    packetHandler.OnReceive(eventArgs.NetState, packetReader);

                    // 返回内存池
                    s_ProcessorBuffers.ReleaseBuffer(extendData.ProcessReceiveData.PacketBuffer);

                    // 恢复原始数据状态
                    extendData.ProcessReceiveData.PacketBuffer = null;
                    extendData.ProcessReceiveData.Remaining    = WORLD_HEAD_SIZE;

                    // 获取剩下的数据长度
                    iReceiveBufferLength = receiveQueueBuffer.Length;
                }
            }
        }
Ejemplo n.º 11
0
			public PacketOverrideRegistryEncoder(IPacketEncoder successor)
			{
				_Successor = successor;
			}
Ejemplo n.º 12
0
 public void _ReadFromStream(IPacketEncoder content)
 {
 }
Ejemplo n.º 13
0
        public void Receive(TransportFile file)
        {
            TaskFactory taskFactory = new TaskFactory();

            taskFactory.StartNew(() =>
            {
                LoggerFactory.Debug("start receive file:id={0}", file.ID);
                string tmpPath = file.SavePath + "." + Path.GetRandomFileName().Replace(".", "") + ".lamim";
                FileStream fs  = null;
                try
                {
                    fs = new FileStream(tmpPath, FileMode.Create);
                }
                catch (Exception e)
                {
                    OnError(Errors.FileOpenError, "打开文件失败:" + tmpPath, file, e);
                    return;
                }
                LoggerFactory.Debug("opened file:" + tmpPath);

                LoggerFactory.Debug("try connect remote:remote={0}, port={1}", file.Remote, file.Port);
                TcpClient tcpClient = null;
                NetworkStream ns    = null;
                try
                {
                    tcpClient = new TcpClient(AddressFamily.InterNetwork)
                    {
                        ReceiveBufferSize = this.ReceiveBufferSize
                    };

                    tcpClient.Connect(file.Remote, file.Port);

                    ns = tcpClient.GetStream();
                }
                catch (Exception e)
                {
                    OnError(Errors.NetworkError, "连接失败", file, e);
                    return;
                }
                LoggerFactory.Debug("conneted remote:remote={0}, port={1}", file.Remote, file.Port);

                LoggerFactory.Debug("encode packet, request file:id={0}", file.ID);
                TcpPacket packet    = null;
                EncodeResult result = null;
                try
                {
                    //发送要接受的文件ID
                    TcpPacketRequestFileTransportExtend extend = new TcpPacketRequestFileTransportExtend
                    {
                        EncryptKey = file.PublicKey,
                        FileID     = file.ID
                    };

                    packet = new TcpPacket
                    {
                        Command = TcpPacket.CMD_REQUEST_FILE_TRANSPORT,
                        Extend  = extend
                    };

                    IPacketEncoder encoder = PacketEncoderFactory.CreateEncoder(packet);
                    result = encoder.Encode(null);
                }
                catch (Exception e)
                {
                    OnError(Errors.EncodeError, "请求文件ID包加密失败。" + packet.ToString(), file, e);
                    return;
                }

                LoggerFactory.Debug("send packet, request file:id={0}", file.ID);
                try
                {
                    ns.Write(result.Fragments[0], 0, result.Fragments[0].Length);
                }
                catch (Exception e)
                {
                    OnError(Errors.NetworkError, "请求文件ID包发送失败", file, e);
                    return;
                }

                LoggerFactory.Debug("receive file start:id={0}", file.ID);
                try
                {
                    int len = 0;
                    file.StartTransport();
                    long lastProgressTicks = file.NowTransportTicks;

                    byte[] buff = new byte[this.ReceiveBufferSize];
                    while ((len = ns.Read(buff, 0, buff.Length)) != 0)
                    {
                        fs.Write(buff, 0, len);

                        file.Transported(len);

                        if (file.TransportedLength == file.File.Length ||
                            (DateTime.Now.Ticks - lastProgressTicks) > this._progressChangeInterval) //避免进度太频繁,500ms一次
                        {
                            OnProgressChanged(file);
                            lastProgressTicks = file.NowTransportTicks;
                        }
                    }
                    LoggerFactory.Debug("receive file end:id={0}", file.ID);
                }
                catch (Exception e)
                {
                    OnError(Errors.NetworkError, "文件接收失败", file, e);
                }
                finally
                {
                    LoggerFactory.Debug("close connect and save file:id={0}", file.ID);
                    //关闭连接
                    ns.Close();
                    tcpClient.Close();

                    fs.Flush(true);
                    fs.Close();

                    if (LanFile.Rename(tmpPath, file.SavePath))
                    {
                        //发送接收完毕
                        OnCompleted(file);
                    }
                    else
                    {
                        OnError(Errors.FileWriteError, "文件写入失败", file, null);
                    }
                }
                LoggerFactory.Debug("end receive file:id={0}", file.ID);
            });
        }
Ejemplo n.º 14
0
 public IPacketEncoder SetEncoder(IPacketEncoder encoder)
 {
     _encoder = encoder;
     return _encoder;
 }
Ejemplo n.º 15
0
 public void _WriteToStream(IPacketEncoder content)
 {
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Constructor of LSPProtocol with specified encoder.
 /// </summary>
 /// <param name="encoder">Encoder to be used with this serial port protocol decoder.</param>
 public LSPProtocol(IPacketEncoder encoder)
 {
  m_encoder=encoder;
  m_rxQueue=new Queue<byte[]>();
  m_serialPort=null;
 }
Ejemplo n.º 17
0
        public void Send(UdpPacket packet)
        {
            if (this._state != ClientState.Working)
            {
                return;
            }

            //异步发送
            IPEndPoint remoteIpEp = new IPEndPoint(packet.Address, packet.Port);

            packet.GenerateID();

            LoggerFactory.Debug("parepare send packet:{0}", packet);

            EncodeResult result = null;

            try
            {
                IPacketEncoder encoder = PacketEncoderFactory.CreateEncoder(packet);
                LoggerFactory.Debug("get encoder:{0}", encoder.GetType().Name);

                result = encoder.Encode(null);
                LoggerFactory.Debug("encode packet:{0}", result);

                if (result.Length > UDP_MAX_BUF_SIZE)
                {
                    //超过大小的分包处理
                    MultiUdpPacket mpacket = new MultiUdpPacket(result.Fragments[0]);
                    mpacket.ID       = packet.ID;
                    mpacket.ParentID = packet.ID;

                    encoder = PacketEncoderFactory.CreateEncoder(mpacket);
                    LoggerFactory.Debug("get encoder:{0}", encoder.GetType().Name);

                    result = encoder.Encode(UDP_MAX_BUF_SIZE - MultiUdpPacket.HEAD_SIZE);
                    LoggerFactory.Debug("encode packet:{0}", result);
                }
            }
            catch (Exception e)
            {
                OnSendPackage(packet, false);
                OnError(Errors.EncodeError, "加密包错误。", e);
            }

            try
            {
                for (int i = 0; i < result.Fragments.Count; i++)
                {
                    byte[]    buf   = result.Fragments[i];
                    SendState state = new SendState();
                    state.LastPacket = i == result.Fragments.Count - 1;
                    state.Packet     = packet;
                    _client.BeginSend(buf, buf.Length, remoteIpEp, new AsyncCallback(AsyncSendHandler), state);
                    Thread.Sleep(20);//稍微等待一下,避免丢包
                }
            }
            catch (Exception e)
            {
                OnSendPackage(packet, false);
                OnError(Errors.NetworkError, "发送包错误。", e);
            }
        }