示例#1
0
        public void TestBase(
            IPacketFilter filter,
            int dataSize)
        {
            NetDataWriter writer = new NetDataWriter();

            byte[] data = GetData(dataSize);

            foreach (var item in data)
            {
                writer.Write(item);
            }

            NetPacket packet = NetPool.PacketPool.Alloc(PacketProperty.UserData, writer);

            var encodedPacket = filter.Encode(packet);
            var decodedPacket = filter.Decode(encodedPacket);

            NetDataReader reader = new NetDataReader(decodedPacket);

            Assert.GreaterOrEqual(decodedPacket.Size, packet.Size);

            for (int i = 0; i < data.Length; i++)
            {
                Assert.AreEqual(data[i], reader.ReadByte());
            }
        }
示例#2
0
 public void RemovePacketFilter(IPacketFilter filter)
 {
     lock (packetFilters)
     {
         packetFilters.Remove(filter);
     }
 }
示例#3
0
 public void AddPacketFilter(IPacketFilter filter)
 {
     lock (packetFilters)
     {
         packetFilters.Add(filter);
     }
 }
示例#4
0
        public override void SendAsync(NetPacket poolingPacket)
        {
            IPacketFilter filter = _channelOption.PacketFilter;

            while (filter != null)
            {
                poolingPacket = filter.Encode(poolingPacket);
                filter        = filter.NextFilter;
            }

            Interlocked.Increment(ref _statistic.TcpPacketSentCount);

            lock (_sendedList)
            {
                if (_sendedList.Count > 0)
                {
                    // 전송중임
                    _sendWaitQueue.Add(poolingPacket);
                    return;
                }

                _sendedBufferList.Push(new ArraySegment <byte>(poolingPacket.RawData, 0, poolingPacket.Size));
                _sendedList.Add(poolingPacket);
            }

            SendAsync(_sendedBufferList);
        }
示例#5
0
 protected void Init()
 {
     ExpectedResponse   = Response.Single;
     TimeoutValue       = PacketParser.DefaultParseTimeout;
     DestinationAddress = null;
     DestinationNode    = null;
     Filter             = null;
 }
示例#6
0
        public AsyncSendResult BeginSend(XBeeRequest request, IPacketFilter filter = null, int timeout = 5000)
        {
            var responseListener = new PacketListener(filter, timeout);

            AddPacketListener(responseListener);
            SendRequest(request);
            return(new AsyncSendResult(this, responseListener));
        }
示例#7
0
 private void configureToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (this.checkedListBoxFilters.SelectedItem != null)
     {
         IPacketFilter filter = (IPacketFilter)this.checkedListBoxFilters.SelectedItem;
         //filter.Configure();
     }
     this.updateFilters();
 }
示例#8
0
        public void ReplacePacketFilter(IPacketFilter currentFilter, IPacketFilter newFilter)
        {
            lock (packetFilters)
            {
                int index = packetFilters.IndexOf(currentFilter);

                packetFilters[index] = newFilter;
            }
        }
示例#9
0
        public PacketListener(IPacketFilter filter = null, int timeout = 5000, ResponseHandler responseHandler = null)
        {
            Filter = filter;
            Packets = new ArrayList();
            FinishedFlag = new AutoResetEvent(false);
            ResponseHandler = responseHandler;

            if (timeout > 0)
                TimeoutTimer = new Timer(s => OnTimeout(), null, timeout, -1);
        }
示例#10
0
        public PacketListener(IPacketFilter filter = null, int timeout = 5000, ResponseHandler responseHandler = null)
        {
            Filter          = filter;
            Packets         = new ArrayList();
            FinishedFlag    = new AutoResetEvent(false);
            ResponseHandler = responseHandler;

            if (timeout > 0)
            {
                TimeoutTimer = new Timer(s => OnTimeout(), null, timeout, -1);
            }
        }
示例#11
0
 protected void InitFilter(XBeeRequest request)
 {
     if (Filter == null)
     {
         Filter = request is AtCommand
                    ? new AtResponseFilter((AtCommand)request)
                    : new PacketIdFilter(request);
     }
     else if (Filter is PacketIdFilter)
     {
         (Filter as PacketIdFilter).ExpectedPacketId = request.FrameId;
     }
 }
示例#12
0
        public XBeeResponse[] CollectResponses(int timeout = -1, IPacketFilter filter = null)
        {
            var listener = new PacketListener(filter);

            try
            {
                AddPacketListener(listener);
                return(listener.GetPackets(timeout));
            }
            finally
            {
                RemovePacketListener(listener);
            }
        }
示例#13
0
        /// <summary>
        /// 버퍼를 입력하여 패킷 단위로 읽어서 처리합니다.
        /// </summary>
        /// <param name="buffer">읽을 버퍼 (보통 채널을 통해 받은 데이터 버퍼)</param>
        /// <param name="totalReceivedSize">버퍼에서 사용되는 크기</param>
        /// <param name="packetFilter">패킷필터</param>
        /// <returns>처리가 완료된 buffer의 offset. 에러가 난 경우 -1</returns>
        protected int ReadPacket(byte[] buffer, int totalReceivedSize, IPacketFilter packetFilter)
        {
            int offset     = 0;
            int remainSize = totalReceivedSize;

            while (remainSize >= NetPacket.HeaderSize)
            {
                int packetSize = BitConverter.ToUInt16(buffer, offset);

                // 최대 패킷크기를 초과했으니 에러
                if (packetSize >= NetPacket.MaxTcpPacketSize)
                {
                    Close();
                    return(-1);
                }

                // 받은 사이즈가 실제 패킷사이즈보다 작으니 기다리자
                if (remainSize < packetSize)
                {
                    break;
                }

                NetPacket packet = NetPool.PacketPool.Alloc(packetSize);
                Buffer.BlockCopy(buffer, offset, packet.RawData, 0, packetSize);

                // 패킷을 가공하자
                IPacketFilter filter = packetFilter;
                while (filter != null)
                {
                    packet = filter.Decode(packet);
                    filter = filter.NextFilter;
                }

                // 유저 패킷 처리
                OnPacketReceived(packet);

                offset     += packetSize;
                remainSize -= packetSize;

                Interlocked.Increment(ref _statistic.PacketReceivedCount);
            }

            return(offset);
        }
示例#14
0
 public void AddFilter(IPacketFilter filter, int position)
 {
     this.filter.Insert(position, filter);
 }
示例#15
0
 public void MoveFilter(IPacketFilter filter, int newPosition)
 {
     this.filter.Remove(filter);
     this.filter.Insert(newPosition, filter);
 }
示例#16
0
        public bool SendPendingPacket()
        {
            // 응답패킷을 보내야 한다면
            if (_sendAcks == true)
            {
                // lock에 비용이 많이드므로 먼저 체크한번 하고 나중에 또 체크하자
                lock (_ackPacket)
                {
                    if (_sendAcks == true)
                    {
                        _sendAcks = false;

                        IPacketFilter filter = _channelOption.PacketFilter;
                        if (filter != null)
                        {
                            var poolingPacket = NetPool.PacketPool.Alloc(_ackPacket, 0);
                            try
                            {
                                while (filter != null)
                                {
                                    poolingPacket = filter.Encode(poolingPacket);
                                    filter        = filter.NextFilter;
                                }

                                _udpChannel.SendTo(poolingPacket.RawData, 0, poolingPacket.Size, UdpChannel.SendMode.Buffered);
                            }
                            finally
                            {
                                NetPool.PacketPool.Free(poolingPacket);
                            }
                        }
                        else
                        {
                            _udpChannel.SendTo(_ackPacket.RawData, 0, _ackPacket.Size, UdpChannel.SendMode.Buffered);
                        }
                    }
                }
            }

            lock (_pendingPackets)
            {
                long nowTicks = DateTime.UtcNow.Ticks;

                lock (_sendQueue)
                {
                    while (_sendQueue.Count > 0)
                    {
                        int relate = NetUtil.RelativeSequenceNumber(_localSequence, _localWindowStart);
                        if (relate >= WindowSize)
                        {
                            break;
                        }

                        NetPacket packet = _sendQueue.Dequeue();

                        packet.Sequence = (ushort)_localSequence;
                        _pendingPackets[_localSequence % WindowSize].Init(packet, nowTicks);
                        _localSequence = (_localSequence + 1) % NetPacket.MaxSequence;
                    }
                }

                for (int pendingSeq = _localWindowStart; pendingSeq != _localSequence; pendingSeq = (pendingSeq + 1) % NetPacket.MaxSequence)
                {
                    if (_pendingPackets[pendingSeq % WindowSize].TrySend(
                            nowTicks,
                            _channelOption.RudpDisconnectTimeout,
                            _udpChannel,
                            _statistic) == false)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
示例#17
0
        public bool SendPendingPacket()
        {
            if (_reliable && _sendQueue.Count == 0)
            {
                long currentTime    = DateTime.UtcNow.Ticks;
                long packetHoldTime = currentTime - _lastPacketSendTime;
                if (packetHoldTime < _udpChannel.ResendDelay * TimeSpan.TicksPerMillisecond)
                {
                    return(true);
                }

                var packet = _lastPacket;
                if (packet != null)
                {
                    _lastPacketSendTime = currentTime;
                    _udpChannel.SendTo(packet.RawData, 0, packet.Size, UdpChannel.SendMode.Buffered);
                }
            }
            else
            {
                lock (_sendQueue)
                {
                    while (_sendQueue.Count > 0)
                    {
                        NetPacket packet = _sendQueue.Dequeue();
                        _localSequence  = (_localSequence + 1) % NetPacket.MaxSequence;
                        packet.Sequence = (ushort)_localSequence;

                        _udpChannel.SendTo(packet.RawData, 0, packet.Size, UdpChannel.SendMode.Buffered);

                        if (_reliable && _sendQueue.Count == 0)
                        {
                            _lastPacketSendTime = DateTime.UtcNow.Ticks;
                            _lastPacket         = packet;
                        }
                        else
                        {
                            NetPool.PacketPool.Free(packet);
                        }
                    }
                }
            }

            if (_reliable && _mustSendAck)
            {
                _mustSendAck        = false;
                _ackPacket.Sequence = _remoteSequence;

                IPacketFilter filter = _channelOption.PacketFilter;
                if (filter != null)
                {
                    var poolingPacket = NetPool.PacketPool.Alloc(_ackPacket, 0);
                    try
                    {
                        while (filter != null)
                        {
                            poolingPacket = filter.Encode(poolingPacket);
                            filter        = filter.NextFilter;
                        }

                        _udpChannel.SendTo(poolingPacket.RawData, 0, poolingPacket.Size, UdpChannel.SendMode.Buffered);
                    }
                    finally
                    {
                        NetPool.PacketPool.Free(poolingPacket);
                    }
                }
                else
                {
                    _udpChannel.SendTo(_ackPacket.RawData, 0, _ackPacket.Size, UdpChannel.SendMode.Buffered);
                }
            }

            return(true);
        }
示例#18
0
 protected void InitFilter(XBeeRequest request)
 {
     if (Filter == null)
     {
         Filter = request is AtCommand
                    ? new AtResponseFilter((AtCommand)request)
                    : new PacketIdFilter(request);
     }
     else if (Filter is PacketIdFilter)
     {
         (Filter as PacketIdFilter).ExpectedPacketId = request.FrameId;
     }
 }
示例#19
0
 public void RemoveFilter(IPacketFilter filter)
 {
     this.filter.Remove(filter);
 }
示例#20
0
        public override void SendAsync(NetPacket poolingPacket)
        {
            var channel = GetChannel(poolingPacket.DeliveryMethod);
            if (channel == null)
            {
                NetPool.PacketPool.Free(poolingPacket);
                return;
            }

            int mtu = Mtu;
            if (poolingPacket.Size > mtu)
            {
                // 보낼수 있는 한계보다 큰 패킷이므로 쪼개서 보내자
                Interlocked.Increment(ref _statistic.UdpFragmentCount);

                try
                {
                    ushort currentFramentId = _fragments.GenerateId();

                    int headerSize = NetPacket.GetHeaderSize(poolingPacket.Property);
                    int dataSize = poolingPacket.Size - headerSize;

                    int maximumSize = mtu - headerSize;
                    int maximumDataSize = maximumSize - NetPacket.FragmentHeaderSize;
                    int totalPackets = dataSize / maximumDataSize + (dataSize % maximumDataSize == 0 ? 0 : 1);

                    for (ushort partIdx = 0; partIdx < totalPackets; partIdx++)
                    {
                        int sendLength = dataSize > maximumDataSize ? maximumDataSize : dataSize;

                        NetPacket p = NetPool.PacketPool.Alloc(sendLength + NetPacket.FragmentedHeaderTotalSize);
                        p.Property = poolingPacket.Property;
                        p.DeliveryMethod = poolingPacket.DeliveryMethod;
                        p.P2pSessionId = poolingPacket.P2pSessionId;
                        p.FragmentId = currentFramentId;
                        p.FragmentPart = partIdx;
                        p.FragmentsTotal = (ushort)totalPackets;
                        p.MarkFragmented();

                        Buffer.BlockCopy(poolingPacket.RawData, headerSize + partIdx * maximumDataSize, p.RawData, NetPacket.FragmentedHeaderTotalSize, sendLength);

                        IPacketFilter f = _channelOption.PacketFilter;
                        while (f != null)
                        {
                            p = f.Encode(p);
                            f = f.NextFilter;
                        }

                        channel.SendAsync(p);

                        dataSize -= sendLength;
                    }
                }
                finally
                {
                    NetPool.PacketPool.Free(poolingPacket);
                }

                return;
            }

            IPacketFilter filter = _channelOption.PacketFilter;
            while (filter != null)
            {
                poolingPacket = filter.Encode(poolingPacket);
                filter = filter.NextFilter;
            }

            Interlocked.Increment(ref _statistic.UdpPacketSentCount);

            channel.SendAsync(poolingPacket);
        }
示例#21
0
 public IRequest Use(IPacketFilter filter)
 {
     Filter = filter;
     return(this);
 }
示例#22
0
 public void RemoveFilter(IPacketFilter filter)
 {
     this.filter.Remove(filter);
 }
示例#23
0
 public void MoveFilter(IPacketFilter filter, int newPosition)
 {
     this.filter.Remove(filter);
     this.filter.Insert(newPosition, filter);
 }
示例#24
0
 /// <summary>
 /// Fügt einen Filter an der letzten stelle ein, die Reihenfolge ist gleichzeitig die Priorität
 /// </summary>
 /// <param name="filter"></param>
 public void AddFilter(IPacketFilter filter)
 {
     this.filter.Add(filter);
 }
示例#25
0
        private async Task <NetClient> WorkClient(IPacketFilter filter, bool isServiceUdp, int sendCount)
        {
            NetClient client = new NetClient(new ClientOption()
            {
                TcpServerAddress = "127.0.0.1",
                TcpServerPort    = 9000,
                IsServiceUdp     = isServiceUdp,
                UdpServerAddress = "127.0.0.1",
                UdpServerPort    = 9001,
                PacketFilter     = filter
            });

            int receivedUnreliableCount = 0;
            var tcs = new TaskCompletionSource <string>();

            client.OnReceived += (NetDataReader reader) =>
            {
                string text = reader.ReadString();

                if (text == "Finish")
                {
                    tcs.SetResult(text);
                }
                else if (text == "Unreliable")
                {
                    receivedUnreliableCount++;
                }
                else
                {
                    Assert.AreEqual($"Hello Client{client.SessionId}", text);
                }

                return(Task.CompletedTask);
            };

            client.OnErrored += (e) =>
            {
                tcs.SetException(e);
            };

            client.OnClosed += () =>
            {
                //tcs.SetException(new Exception("session closed"));
                tcs.TrySetException(new Exception("session closed"));
            };

            Task.Factory.StartNew(async() =>
            {
                await Task.Delay(100);
                Stopwatch sw = Stopwatch.StartNew();
                while (client.State != SessionState.Closed)
                {
                    sw.Stop();
                    client.Update((int)sw.ElapsedMilliseconds);
                    sw.Restart();
                    await Task.Delay(30);
                }
            }).DoNotAwait();

            var connected = await client.ConnectAsync(null);

            Assert.True(connected);

            for (int i = 0; i < sendCount; i++)
            {
                var writer = NetPool.DataWriterPool.Alloc();
                try
                {
                    if (i < sendCount - 1)
                    {
                        writer.Write("12345678901234567890123456789012345678901234567890123");
                    }
                    else
                    {
                        writer.Write("Finish");
                    }

                    client.SendAsync(writer, DeliveryMethod.Tcp);
                }
                finally
                {
                    NetPool.DataWriterPool.Free(writer);
                }

                if (isServiceUdp)
                {
                    writer = NetPool.DataWriterPool.Alloc();
                    try
                    {
                        writer.Write("Unreliable");

                        client.SendAsync(writer, DeliveryMethod.Unreliable);
                    }
                    finally
                    {
                        NetPool.DataWriterPool.Free(writer);
                    }
                }
            }

            await Task.Delay(1000);

            await tcs.Task;

            Assert.True(tcs.Task.IsCompletedSuccessfully);
            Assert.AreEqual("Finish", tcs.Task.Result);

            if (isServiceUdp)
            {
                Console.WriteLine($"receivedUnreliableCount : {receivedUnreliableCount}");
            }

            return(client);
        }
示例#26
0
 public IRequest Use(IPacketFilter filter)
 {
     Filter = filter;
     return this;
 }
示例#27
0
 public void BeginSend(XBeeRequest request, ResponseHandler responseHandler, IPacketFilter filter = null, int timeout = 5000)
 {
     AddPacketListener(new PacketListener(filter, timeout, responseHandler));
     SendRequest(request);
 }
示例#28
0
 public AsyncSendResult BeginSend(XBeeRequest request, IPacketFilter filter = null, int timeout = 5000)
 {
     var responseListener = new PacketListener(filter, timeout);
     AddPacketListener(responseListener);
     SendRequest(request);
     return new AsyncSendResult(this, responseListener);
 }
示例#29
0
 public void BeginSend(XBeeRequest request, ResponseHandler responseHandler, IPacketFilter filter = null, int timeout = 5000)
 {
     AddPacketListener(new PacketListener(filter, timeout, responseHandler));
     SendRequest(request);
 }
示例#30
0
 /// <summary>
 /// Fügt einen Filter an der letzten stelle ein, die Reihenfolge ist gleichzeitig die Priorität
 /// </summary>
 /// <param name="filter"></param>
 public void AddFilter(IPacketFilter filter)
 {
     this.filter.Add(filter);
 }
示例#31
0
        public XBeeResponse[] CollectResponses(int timeout = -1, IPacketFilter filter = null)
        {
            var listener = new PacketListener(filter);

            try
            {
                AddPacketListener(listener);
                return listener.GetPackets(timeout);
            }
            finally
            {
                RemovePacketListener(listener);
            }
        }
示例#32
0
 public void AddFilter(IPacketFilter filter, int position)
 {
     this.filter.Insert(position, filter);
 }
示例#33
0
 protected void Init()
 {
     ExpectedResponse = Response.Single;
     TimeoutValue = PacketParser.DefaultParseTimeout;
     DestinationAddress = null;
     DestinationNode = null;
     Filter = null;
 }