Exemple #1
0
 protected void _Receive()
 {
     try {
         while (_client.Available > 0)
         {
             var rawPacket = _netReader.Read(new BinaryReader(_client.GetStream()),
                                             _client.Available);
             if (rawPacket == null)
             {
                 continue;
             }
             rawPacket.remoteEP = (IPEndPoint)_client.Client.RemoteEndPoint;
             _packetForwardService.ForwardPacket(rawPacket);
         }
     } catch (Exception ex) {
         ULogger.Warning($"<{serviceName}> An error occurs when read packet data.", ex);
         _client?.GetStream().Seek(0, SeekOrigin.End);
     }
 }
        private void _UDPRead()
        {
            while (_client.Available != 0)
            {
                // 接收来自远程主机的数据子包,并获取来源地址
                var remoteEP = new IPEndPoint(IPAddress.Any, localPort);
                var data     = _client.Receive(ref remoteEP);
                // [LOG] UDP data length
                if (showLog)
                {
                    ULogger.Info($"<{serviceName}> Udp data received, length = {data.Length}");
                }

                // 获取或创建与远程主机绑定的数据包读取对象
                if (!_netReaders.TryGetValue(remoteEP, out var netReader))
                {
                    _netReaders.Add(remoteEP, netReader = _NetReader.Create(NetType.UDP));
                }

                // 读取并尝试组装子包
                _RawPacket rawPacket;
                try {
                    rawPacket = netReader.Read(new BinaryReader(new MemoryStream(data)),
                                               data.Length);
                } catch (Exception e) {
                    ULogger.Warning(
                        $"<{serviceName}> Received unrecognized or corrupted packet", e);
                    continue;
                }
                if (rawPacket == null)
                {
                    continue;
                }

                // 填入远程主机地址并分发数据包
                rawPacket.remoteEP = remoteEP;
                _packetForwardService.ForwardPacket(rawPacket);
            }
        }