Ejemplo n.º 1
0
        private void OnReceiveSecondary(IAsyncResult ar)
        {
            int size = 0;

            try
            {
                size = secondarySocket.EndReceive(ar);
            }
            catch (ObjectDisposedException)
            {
                // Stop receiving
                return;
            }

            var newPacket = PCapPacket.CreateFromBytes(secondaryByteData, size);

            newPacket.PacketNumber = packetNumber++;
            var diff = DateTime.UtcNow - start;

            newPacket.TimeStampSeconds      = (uint)diff.TotalSeconds;
            newPacket.TimeStampMicroseconds = (uint)((diff.TotalSeconds - (uint)diff.TotalSeconds) * 1000000);
            ReceivedPacket?.Invoke(this, newPacket);

            // Receive again
            try
            {
                secondarySocket.BeginReceive(secondaryByteData, 0, secondaryByteData.Length, SocketFlags.None, new AsyncCallback(OnReceiveSecondary), null);
            }
            catch (ObjectDisposedException)
            {
                // Stop receiving
                return;
            }
        }
Ejemplo n.º 2
0
        public AnvizDevice(TcpClient socket)
        {
            DeviceStream = new AnvizStream(socket);
            DeviceStream.ReceivedPacket += (s, e) =>
            {
                switch (e.ResponseCode)
                {
                case 0x7F:
                    DevicePing?.Invoke(this, null);
                    break;

                case 0xDF:
                    ReceivedRecord?.Invoke(this, new Record(e.DATA, 0));
                    break;

                default:
                    ReceivedPacket?.Invoke(this, e);
                    break;
                }
            };
            DeviceStream.DeviceError += (s, e) =>
            {
                DeviceError?.Invoke(this, e);
            };
        }
Ejemplo n.º 3
0
        private async void Listen()
        {
            while (await _inStream.MoveNext())
            {
                var packet = _inStream.Current;
                // Invoke the event on the main thread
                UnityMainThreadDispatcher.Instance()
                .Enqueue(() =>
                {
                    switch (packet.TypeCase)
                    {
                    case Packet.TypeOneofCase.Authentication:
                        _token = packet.Authentication.ClientToken;
                        // Record.Log($"Received auth {_token}");

                        break;

                    case Packet.TypeOneofCase.CreatePlayer:
                        Record.Log($"Received create player {packet.CreatePlayer}");

                        break;
                    }
                    // Record.Log($"Received {packet}");

                    ReceivedPacket?.Invoke(packet);
                });
            }
        }
Ejemplo n.º 4
0
 private async void ReceiverThreadFunc()
 {
     while (DeviceSocket.Connected && !CancellationTokenSource.IsCancellationRequested)
     {
         Response response = null;
         try
         {
             response = await Response.FromStream(DeviceStream, CancellationTokenSource.Token);
         }
         catch (Exception ex)
         {
             DeviceError?.Invoke(this, ex);
         }
         if (response == null)
         {
             DeviceSocket.Close();
             taskEmitter.TrySetResult(null);
             break;
         }
         if (response.ResponseCode == 0x7F)
         {
             await new PongCommand(response.DeviceID).Send(DeviceStream);
             ReceivedPacket?.Invoke(this, response);
         }
         else if (response.ResponseCode == ResponseCode)
         {
             ResponseCode = 0;
             taskEmitter.TrySetResult(response);
         }
         else
         {
             ReceivedPacket?.Invoke(this, response);
         }
     }
 }
Ejemplo n.º 5
0
 protected void OnReceivedPacket(T packet)
 {
     if (ReceivedPacket != null)
     {
         PacketEventArgs <T> packetEventArgs = new PacketEventArgs <T>(packet);
         ReceivedPacket.Invoke(this, packetEventArgs);
     }
 }
Ejemplo n.º 6
0
 public AnvizDevice(TcpClient socket)
 {
     DeviceStream = new AnvizStream(socket);
     DeviceStream.ReceivedPacket += (s, e) =>
     {
         if (e.ResponseCode == 0x7F)
         {
             DevicePing?.Invoke(this, null);
         }
         else
         {
             ReceivedPacket?.Invoke(this, e);
         }
     };
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Processes the packet stream.
        /// </summary>
        /// <returns>Task.</returns>
        private async Task ProcessPacketStream()
        {
            try
            {
                while (IsConnected && (OutgoingPackets.Count != 0 || TcpClient.Available != 0))
                {
                    while (IsConnected && TcpClient.Available != 0)
                    {
                        ReceivedPacket?.Invoke(this, new PacketEventArgs {
                            Packet = await Packet.ReadFromStreamAsync(TcpClientStream)
                        });

                        IncomingPacketReceieved = true;
                    }


                    if (!IsConnected || !CanSendPacket || OutgoingPackets.Count == 0)
                    {
                        continue;
                    }

                    await OutgoingPackets.Dequeue().WriteToStreamAsync(TcpClientStream);

                    OutgoingPacketCooldown.Restart();
                    IncomingPacketReceieved = false;

                    //// We've successfully sent or recieved data so the keepalive can be pushed back.
                    Keepalive.Reset();
                }
            }
            catch
            {
                // Lost connection with the server
                // No handling is necessary here as the TCPClient will set Connected to false.
                ServerConnectionDropped?.Invoke(this, new ServerConnectionEventArgs {
                    Message = "Connection to the server has been lost.", Status = ServerConnectionStatusEnum.Disconnected, Timestamp = DateTime.Now
                });
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Цикл чтения пакетов из соединения
        /// </summary>
        /// <returns></returns>
        public async Task ReadAsync()
        {
            try
            {
                while (true)
                {
                    short bodyLength = await ReadBodyLengthAsync();

                    byte[] body = new byte[bodyLength];
                    await ReadBodyAsync(body, bodyLength);

                    var packet = new Packet(1, body);

                    ReceivedPacket?.Invoke(packet);
                }
            }
            catch (Exception ex)
            {
                logger.Error($"Ошибка при чтении пакета: {ex.Message}");
                //TODO: Тут надо новерно закрывать соединение
            }
        }
Ejemplo n.º 9
0
        private async void ReceiverThreadFunc()
        {
            while (!CancellationTokenSource.IsCancellationRequested)
            {
                var response = await Response.FromStream(DeviceStream, CancellationTokenSource.Token);

                if (response == null)
                {
                    DeviceSocket.Close();
                    taskEmitter.TrySetResult(null);
                    break;
                }
                else if (response.ResponseCode == ResponseCode)
                {
                    ResponseCode = 0;
                    taskEmitter.TrySetResult(response);
                }
                else
                {
                    ReceivedPacket?.Invoke(this, response);
                }
            }
        }
Ejemplo n.º 10
0
        private void Receive()
        {
            Active = true;

            Task.Run(() => {
                while (Active)
                {
                    EndPoint newClient = new IPEndPoint(IPAddress.Any, 0);
                    byte[] bytes       = new byte[4096];
                    int length         = _listener.ReceiveFrom(bytes, ref newClient);

                    Packet p       = new Packet(bytes.ToList().GetRange(0, length));
                    UdpSocket user = new UdpSocket(newClient);

                    if (Clients.Where(c => c.RemoteEndPoint.ToString() == newClient.ToString()).ToList().Count == 0)
                    {
                        Clients.Add(user);
                        ClientConnectionRequested?.Invoke(user);
                    }

                    ReceivedPacket?.Invoke(user, p);
                }
            });
        }
Ejemplo n.º 11
0
 void OnReceivedPacket(UdpReceiveResult udpResult)
 {
     ReceivedPacket?.Invoke(null, udpResult);
 }