Beispiel #1
0
    private void handlePingPacket(PingPacket pingPacket)
    {
        // reply pingPacket
        int id = pingPacket.id;

        sendPacket(new PingPacket(id));
    }
        public static Packet ConvertToPacket(this byte[] buffer, SocketReceivedResult socketReceiveResult)
        {
            Packet receivedPacket = null;
            var    eventType      = buffer.GetSocketEventType();

            switch (eventType)
            {
            case PacketTypeEnum.Connection:
                receivedPacket = new ConnectionPacket();
                break;

            case PacketTypeEnum.Ping:
                receivedPacket = new PingPacket();
                break;

            case PacketTypeEnum.Disconnect:
                receivedPacket = new DisconnectPacket();
                break;

            case PacketTypeEnum.Movement:
                receivedPacket = new MovementPacket();
                break;

            default:
                Log.Error("Unknown packet type, cannot handle them");
                break;
            }

            receivedPacket.Deserialize(buffer);
            receivedPacket.SetHeader(eventType, socketReceiveResult.RemoteEndPoint);

            return(receivedPacket);
        }
Beispiel #3
0
        void HandlePing(PingPacket p)
        {
            var now  = TimeUtils.NowMillis;
            var diff = now - p.Millis;

            latency.OnNext(diff);
        }
Beispiel #4
0
 //PingPacket
 private static void HandlePacket(PingPacket packet)
 {
     if (packet.RequestingReply)
     {
         PacketSender.SendPing();
     }
 }
Beispiel #5
0
 public void OnPing(ILoginClient client, PingPacket pingPacket)
 {
     if (!pingPacket.IsTimeOut)
     {
         _loginPacketFactory.SendPong(client, pingPacket.Time);
     }
 }
 public void OnPing(IClusterClient client, PingPacket pingPacket)
 {
     if (!pingPacket.IsTimeOut)
     {
         _clusterPacketFactory.SendPong(client, pingPacket.Time);
     }
 }
        // Pings are special, quasi-reliable packets.
        // We send them to trigger responses that validate our connection is alive
        // An unacked ping should never be the sole cause of a disconnect.
        // Rather, the responses will reset our pingsSinceAck, enough unacked
        // pings should cause a disconnect.
        private void SendPing()
        {
            ushort id = (ushort)Interlocked.Increment(ref lastIDAllocated);

            byte[] bytes = new byte[3];
            bytes[0] = (byte)UdpSendOption.Ping;
            bytes[1] = (byte)(id >> 8);
            bytes[2] = (byte)id;

            PingPacket pkt;

            if (!this.activePingPackets.TryGetValue(id, out pkt))
            {
                pkt = PingPacket.GetObject();
                if (!this.activePingPackets.TryAdd(id, pkt))
                {
                    throw new Exception("This shouldn't be possible");
                }
            }

            pkt.Stopwatch.Restart();

            WriteBytesToConnection(bytes, bytes.Length);

            Statistics.LogReliableSend(0, bytes.Length);
        }
Beispiel #8
0
            protected override void Evolve(ref Actions newState, Entity currentState, int generation, EntityRandom randomSource, EntityRanges ranges, bool isInconsistent)
            {
                if (!amPong)
                {
                    newState.Broadcast(0, Helper.SerializeToArray(p.Increment()));
                    amPong = true;

                    p = p.Increment();
                }
                else
                {
                    PingPacket data = null;
                    if (currentState.InboundMessages != null)
                    {
                        foreach (var m in currentState.InboundMessages)
                        {
                            if (m.Sender == currentState.ID)
                            {
                                continue;
                            }
                            data = Helper.Deserialize(m.Payload) as PingPacket;
                            if (data != null)
                            {
                                break;
                            }
                        }
                    }
                    if (data == null)
                    {
                        return;
                    }
                    newState.Broadcast(0, Helper.SerializeToArray(data.Increment()));
                    p = data;
                }
            }
Beispiel #9
0
        public void TestSerde()
        {
            var a = new PingPacket(1234);
            var b = SerializeAndDeserialize(a);

            Assert.Equal(a, b);
        }
Beispiel #10
0
        public void OnReceivePacket(DatagramPacket datagramPacket)
        {
            byte[] dpData = datagramPacket.Data;

            int sType          = PacketCheck.CheckSType(datagramPacket);
            int remoteClientId = BitConverter.ToInt32(dpData, 9);

            if (sType == PacketType.PingPacket)
            {
                PingPacket pingPacket = new PingPacket(datagramPacket);
                SendPingPacket2(pingPacket.PingId, datagramPacket.Host, datagramPacket.Port);
                CurrentSpeed = pingPacket.DownloadSpeed * 1024;
            }
            else if (sType == PacketType.PingPacket2)
            {
                PingPacket2 pingPacket2 = new PingPacket2(datagramPacket);
                LastReceivePingTime = DateTimeExtensions.CurrentTimeMillis();
                long?t = PingTable[pingPacket2.PingId];
                if (t != null)
                {
                    PingDelay = (int)(DateTimeExtensions.CurrentTimeMillis() - t);
                    string protocal = "udp";
                    Console.WriteLine("delay_" + protocal + " " + PingDelay + "ms " + datagramPacket.Host + ":" + datagramPacket.Port);
                }
            }
        }
Beispiel #11
0
 private void OnPing(PingPacket ping)
 {
     _net.SendPacket(new PongPacket
     {
         Serial = ping.Serial,
         Time   = GetTime()
     });
 }
        public void PingPacket()
        {
            string str    = "6a8716423a5d000000";
            var    packet = new PingPacket();

            Assert.Equal(9, packet.Raw.Length);
            var expected = str.StringToByteArray();
        }
        private void OnPing(IncomingPacket packet)
        {
            PingPacket pingPacket = (PingPacket)packet;

            _client.SendPacket(new PongPacket()
            {
                Serial = pingPacket.Serial, Time = _client.GetTimer()
            });
        }
Beispiel #14
0
            public static PingPacket Deserialize(byte[] data)
            {
                PingPacket   rv = new PingPacket();
                MemoryStream ms = new MemoryStream(data);

                using (BinaryReader br = new BinaryReader(ms))
                    rv.header = br.ReadBytes(2);
                return(rv);
            }
Beispiel #15
0
        public static void OnPing(ClusterClient client, INetPacketStream packet)
        {
            var pak = new PingPacket(packet);

            if (!pak.IsTimeOut)
            {
                CommonPacketFactory.SendPong(client, pak.Time);
            }
        }
Beispiel #16
0
        private void ListenForMessages()
        {
            NetIncomingMessage message;

            Console.WriteLine("CLIENT: Listening for messages");
            while (isListening)
            {
                while ((message = client.ReadMessage()) != null)
                {
                    switch (message.MessageType)
                    {
                    case NetIncomingMessageType.Data:
                        // handle custom messages
                        //read
                        PacketTypes type      = (PacketTypes)message.ReadByte();
                        PongPacket  payPacket = PacketHelper.Get <PongPacket>(type);
                        payPacket.Deserialize(message);
                        Console.WriteLine($"We got a packet of: {type} with PingMs {payPacket.PingMs}");

                        //send
                        NetOutgoingMessage msg      = client.CreateMessage();
                        PingPacket         outbound = PacketHelper.Get <PingPacket>(PacketTypes.Ping);
                        outbound.PingMs = DateTime.Now.Millisecond;
                        outbound.Serialize(msg);
                        client.SendMessage(msg, message.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                        Console.WriteLine($"We sent a packet of: {PacketTypes.Ping} with PingMs {outbound.PingMs}");
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        // handle connection status messages
                        //switch (message.SenderConnection.Status) {
                        /* .. */
                        //}
                        Console.WriteLine($"CLIENT: Status Changed = {message.SenderConnection.Status}");
                        break;

                    case NetIncomingMessageType.DebugMessage:
                        // handle debug messages
                        // (only received when compiled in DEBUG mode)
                        Console.WriteLine($"CLIENT: {message.ReadString()}");
                        break;

                    /* .. */
                    case NetIncomingMessageType.WarningMessage:
                        Console.WriteLine($"CLIENT: WARNING: {message}");
                        break;

                    default:
                        Console.WriteLine("CLIENT: unhandled message with type: "
                                          + message.MessageType);
                        break;
                    }
                }
            }
            Console.WriteLine("CLIENT: Done listening for messages");
        }
        public async Task PingClientAsync(int clientId)
        {
            var recipient = _connectionManager.GetClientById(clientId);

            var pingPacket = new PingPacket();
            await _socketManager.SendAsync(
                data : pingPacket.Serialize(),
                recipient : recipient
                );
        }
Beispiel #18
0
        static private IPacket ping(IPacket recieved)
        {
            //string fligsims = string.Join("|", LRMServer.LoadedConfig.allowedFlightSims);
            PingPacket r = new PingPacket()
            {
                serverName = LRMServer.LoadedConfig.LRMServerName,
                serverType = LRMServer.LoadedConfig.ServerType,
            };

            return(r);
        }
Beispiel #19
0
        public async Task PingAsync()
        {
            await _policy.ExecuteAsync(async (content) =>
            {
                await ConnectAsync();

                var Packet = new PingPacket();

                await _embed_channel.WriteAndFlushAsync(Packet);
            }, new Dictionary <string, object>() { { "hld", "PingAsync" } });
        }
Beispiel #20
0
        public void Deserialize()
        {
            var pingPacket = new PingPacket("hello");

            var bytes = PacketSerializer.Serialize(pingPacket);

            var packets = PacketSerializer.Deserialize(bytes);

            Assert.IsTrue(packets.Length == 1);
            Assert.AreEqual("hello", ((PingPacket)packets[0]).contents);
        }
 //PingPacket
 private static void HandlePacket(PingPacket packet)
 {
     if (packet.RequestingReply)
     {
         PacketSender.SendPing();
         PingTime = Globals.System.GetTimeMs();
     }
     else
     {
         Network.Ping = (int)(Globals.System.GetTimeMs() - PingTime) / 2;
     }
 }
Beispiel #22
0
        private static void PingServer(LocalSettings settings)
        {
            var      packet   = new PingPacket();
            DateTime sent     = DateTime.Now;
            var      endPoint = new IPEndPoint(IPAddress.Loopback, settings.NetworkPort);

            Console.WriteLine("-> PING {0}", endPoint);
            SendPacket(packet, endPoint, (sender, e) =>
            {
                Console.WriteLine("<- PONG {0}ms", (int)(DateTime.Now - sent).TotalMilliseconds);
            }, () => Console.WriteLine("Timed out."));
        }
Beispiel #23
0
        /// <summary>
        /// Handle the ping action sent from client.
        /// </summary>
        /// <param name="pingPacket">Ping packet received from client.</param>
        public void OnPing(PingPacket pingPacket)
        {
            Console.WriteLine("Ping Received: " + pingPacket.PingId);

            DataControl.Sender.SendSpeed = pingPacket.DownloadSpeed;

            Ping2Packet ping2Packet = new Ping2Packet(ClientId, pingPacket.PingId);

            Task.Run(async() => {
                await Conn.SendAsync(ping2Packet.Dgram, ClientIPEndPoint);
            });
        }
Beispiel #24
0
        private void RecievePing(PingPacket packet)
        {
            var send        = DateTime.ParseExact(packet.sendDate, Server.DATE_FORMAT, null);
            var recieveDate = DateTime.ParseExact(packet.recieveDate, Server.DATE_FORMAT, null);
            var now         = DateTime.Now;

            var clientLatency = (now.Subtract(send)).Milliseconds / 2;
            var client        = ServerTcpHandler.GetClient(packet.ClientId);

            client.Latency = clientLatency;
            Log.Debug($"Recieved ping from {client.ConnectionId} latency ={clientLatency}");
        }
Beispiel #25
0
        void SendPing()
        {
            var mgr = ConnectionManager.Instance;

            if (mgr == null)
            {
                return;
            }
            var p = new PingPacket(TimeUtils.NowMillis);

            mgr.SendImmediate(p);
        }
Beispiel #26
0
        public void Serialize()
        {
            var pingPacket = new PingPacket("hello");

            var bytes = PacketSerializer.Serialize(pingPacket);

            var header     = 4;
            var packets    = 1;
            var packetSize = Marshal.SizeOf(pingPacket);

            Assert.AreEqual(header + packets + packetSize, bytes.Length);
        }
 public override void UserEventTriggered(IChannelHandlerContext context, object evt)
 {
     if (evt is IdleStateEvent idleStateEvent)
     {
         if (idleStateEvent.State == IdleState.AllIdle)
         {
             var pingPacket = new PingPacket();
             //release?
             ReferenceCountUtil.SafeRelease(idleStateEvent);
             context.WriteAndFlushAsync(pingPacket);
         }
     }
 }
Beispiel #28
0
 /// <summary>
 /// Start an automantic ping task.
 /// </summary>
 public void BeginPing()
 {
     Task.Run(async() => {
         while (true)
         {
             PingId += 1;
             PingPacket pingPacket = new PingPacket(ClientId, PingId, Config.DownloadSpeed, Config.UploadSpeed);
             await Conn.SendAsync(pingPacket.Dgram, ServerIPEndPoint);
             Console.WriteLine("Ping Sent: " + PingId);
             await Task.Delay(1000);
         }
     });
 }
Beispiel #29
0
        public override void HandlePacket(object sender, string packet_raw)
        {
            Packet packet = Packet.Deserialize(packet_raw);

            if (packet.Type == "PingPacket")
            {
                // Handle incoming ping
                PingPacket received_ping = PingPacket.Deserialize(packet_raw);
                Thread.Sleep(1000);
                PingPacket new_pingpacket = new PingPacket(received_ping.Checksum);
                Connection.SendPacket(new_pingpacket);
            }
        }
        private async Task Connect()
        {
            ConnectorFactory connectorFactory = new ConnectorFactory();

            connectorFactory.Uri = new Uri(webSockets ? "ws://localhost:5001/" : "tcp://127.0.0.1:7000");
            for (int i = 0; i < Connections; i++)
            {
                Connector   connector   = connectorFactory.Create();
                Transporter transporter = await connector.Execute(cancellationTokenSource.Token);

                PingPacket pingPacket = new PingPacket(Bytes, Iterations);
                tasks.Add(ExecuteRead(transporter, pingPacket));
                tasks.Add(ExecuteWrite(transporter, pingPacket));
                transporters.Add(transporter);
            }
        }
Beispiel #31
0
        /// <summary>
        ///     Poll the connections.  This just checks on the connection
        ///     every so ofen to perform routine maintenance (sending ping packets, etc).
        /// </summary>
        private bool Poll()
        {
            // Disconnected? :(
            if (m_connected == true || m_connecting == true || m_reconnecting == true)
            {
                m_disconnectTimer = Environment.TickCount;
            }

            // Update connected state.
            lock (m_socket_lock)
            {
                if (m_connected == true && m_socket != null)
                {
                    if (m_socket.Connected == false)
                    {
                        DisposeSocket(true);
                        return false;
                    }
                }
            }

            // Send a ping!
            if (m_waitingForPong == false && m_connectionEstablished == true)
            {
                if (Environment.TickCount - m_timeSinceLastPong > Settings.CONNECTION_PING_INTERVAL || m_timeSinceLastPong == 0)
                {
                    PingPacket packet = new PingPacket();
                    SendPacket(packet);

                    m_timeSinceLastPing = Environment.TickCount;
                    m_waitingForPong = true;
                }
            }

            // Has ping reply timed out?
            else if (m_connectionEstablished == true)
            {
                if (m_waitingForPong == true && Environment.TickCount - m_timeSinceLastPing > Settings.CONNECTION_PING_TIMEOUT_INTERVAL)
                {
                    Logger.Error("Failed to recieve ping within timeout from peer at end point {0}.", LoggerVerboseLevel.Normal, m_endPoint.ToString());
                    DisposeSocket(true);
                    return false;
                }
            }

            // Have we not established connection yet?
            else if (m_connectionEstablished == false)
            {
                if (Environment.TickCount - m_connectionCreateTime > Settings.CONNECTION_ESTABLISH_TIMEOUT_INTERVAL)
                {
                    Logger.Error("Failed to recieve connection packet within timeout from peer at end point {0}.", LoggerVerboseLevel.Normal, m_endPoint.ToString());
                    DisposeSocket(true);
                    return false;
                }
            }
            
            return true;
        }
Beispiel #32
0
        private static void Main(string[] args)
        {
            SetUpLogging();

            IEnumerable<ICrazyradioDriver> crazyradioDrivers = null;

            try
            {
                Log.Debug("Starting Crazyradio USB dongle tests.");

                crazyradioDrivers = CrazyradioDriver.GetCrazyradios();
            }
            catch (Exception ex)
            {
                Log.Error("Error getting Crazyradios.", ex);
            }

            if (crazyradioDrivers != null && crazyradioDrivers.Any())
            {
                var crazyradioDriver = crazyradioDrivers.First();

                try
                {
                    crazyradioDriver.Open();

                    var scanResults = crazyradioDriver.ScanChannels();
                    if (scanResults.Any())
                    {
                        var firstScanResult = scanResults.First();

                        var dataRateWithCrazyflie = firstScanResult.DataRate;
                        var channelWithCrazyflie = firstScanResult.Channels.First();

                        crazyradioDriver.DataRate = dataRateWithCrazyflie;
                        crazyradioDriver.Channel = channelWithCrazyflie;

                        var pingPacket = new PingPacket();
                        var pingPacketBytes = pingPacket.GetBytes();

                        var crazyRadioMessenger = new CrazyradioMessenger(crazyradioDriver);

                        var loop = true;
                        while (loop)
                        {
                            // test 2 (using CTRP lib)
                            {
                                Log.InfoFormat("Ping Packet Bytes: {0}", BitConverter.ToString(pingPacketBytes));

                                var ackPacket = crazyRadioMessenger.SendMessage(new PingPacket());
                                var ackPacketBytes = ackPacket.GetBytes();

                                Log.InfoFormat("ACK Response Bytes (using CTRP): {0}", BitConverter.ToString(ackPacketBytes));
                            }

                            if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Spacebar)
                            {
                                loop = false;
                            }
                        }
                    }
                    else
                    {
                        Log.Warn("No Crazyflie Quadcopters found!");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Error testing Crazyradio.", ex);
                }
                finally
                {
                    crazyradioDriver.Close();
                }
            }
            else
            {
                Log.Warn("No Crazyradio USB dongles found!");
            }

            Log.Info("Sleepy time...Hit space to exit.");

            var sleep = true;
            while (sleep)
            {
                if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Spacebar)
                {
                    sleep = false;
                }
            }
        }
        public void TestPingCopter()
        {
            if (crazyradioDrivers != null && crazyradioDrivers.Any())
            {
                // Use the first available Crazyradio USB dongle returned from the scan in the initialize test methods call.
                var crazyradioDriver = crazyradioDrivers.First();

                try
                {
                    // Open the Crazyradio USB dongle device for communication and configuration.
                    crazyradioDriver.Open();

                    // Get Crazyradio USB dongle to scann for communication channels of Crazyflie quadcopters.
                    var scanResults = crazyradioDriver.ScanChannels();
                    if (scanResults.Any())
                    {
                        // Pick the first result...
                        var firstScanResult = scanResults.First();

                        // Results are grouped by DataRate...
                        var dataRateWithCrazyflie = firstScanResult.DataRate;
                        // Pick the first communication RadioChannel...
                        var channelWithCrazyflie = firstScanResult.Channels.First();

                        // Set the CrazyradioDriver to use the above communication RadioChannel and DataRate to communicate with the Crazyflie quadcopter using that DataRate and RadioChannel...
                        crazyradioDriver.DataRate = dataRateWithCrazyflie;
                        crazyradioDriver.Channel = channelWithCrazyflie;

                        // Create a ping packet to set to the Crazyflie we're going to ping 10 times.
                        // We can reuse this same ping packet object. No point in creating a new one for each ping.
                        var pingPacket = new PingPacket();

                        // Get ping packet bytes just to print out.
                        var pingPacketBytes = pingPacket.GetBytes();

                        int i = 0;
                        while (i < 10)
                        {
                            // Print out the ping packet bytes.
                            Console.WriteLine("Ping Packet Bytes: {0}", BitConverter.ToString(pingPacketBytes));

                            // Send the ping packet bytes via the CrazyradioDriver and get ACK (acknowledgement) response bytes.
                            var ackResponse = crazyradioDriver.SendData(pingPacketBytes);

                            // Print out the ACK response bytes.
                            Console.WriteLine("ACK Response Bytes (using driver): {0}", BitConverter.ToString(ackResponse));

                            // one more time!
                            i++;
                        }
                    }
                    else
                    {
                        throw new Exception("No Crazyflie Quadcopters found!");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error testing Crazyradio.", ex);
                }
                finally
                {
                    // Close the Crazyradio USB dongle for communication.
                    crazyradioDriver.Close();
                }
            }
            else
            {
                throw new Exception("No Crazyradio USB dongles found!");
            }

            Assert.IsTrue(true);
        }