Exemplo n.º 1
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 static void Main(string[] args)
 {
     using (var game = new Pong())
     {
         game.Run();
     }
 }
Exemplo n.º 2
0
        public void Start(int count, Pong pong)
        {
            _initialCount = _pingCount = count;
            _watch = Stopwatch.StartNew();

            pong.Ping(this);
        }
Exemplo n.º 3
0
 public void Setup()
 {
     _ping = new PingActor();
     _ping2 = new PingActor();
     _ping3 = new PingActor();
     _ping4 = new PingActor();
     _pong = new PongActor();
 }
Exemplo n.º 4
0
    static void Main(string[] args)
    {
        using (Pong game = new Pong())
        {
#if !DEBUG
            game.IsFullScreen = true;
#endif
            game.Run();
        }
    }
Exemplo n.º 5
0
        private void Consume(Pong pong)
        {
            _pingCount--;
            if (_pingCount == 0)
            {
                _watch.Stop();
                Trace.WriteLine("Ping -> Pong " + _pingCount + " On Thread: " + Thread.CurrentThread.ManagedThreadId);

                long perSecond = ((long) _initialCount*2000)/(_watch.ElapsedMilliseconds == 0 ? 1 : _watch.ElapsedMilliseconds);
                Trace.WriteLine("Elapsed Time = " + _watch.ElapsedMilliseconds + "ms, Messages Per Second = " + perSecond);
                return;
            }

            if (_pingCount%50000 == 0)
            {
                Trace.WriteLine("Ping -> Pong " + _pingCount + " On Thread: " + Thread.CurrentThread.ManagedThreadId);
            }

            pong.Ping(this);
        }
Exemplo n.º 6
0
        private void Consume(Pong pong)
        {
            _pingCount--;
            if (_pingCount == 0)
            {
                _watch.Stop();
                Trace.WriteLine("Ping -> Pong " + _pingCount + " On Thread: " + Thread.CurrentThread.ManagedThreadId);

                long perSecond = ((long)_initialCount * 2000) / (_watch.ElapsedMilliseconds == 0 ? 1 : _watch.ElapsedMilliseconds);
                Trace.WriteLine("Elapsed Time = " + _watch.ElapsedMilliseconds + "ms, Messages Per Second = " + perSecond);
                return;
            }

            if (_pingCount % 50000 == 0)
            {
                Trace.WriteLine("Ping -> Pong " + _pingCount + " On Thread: " + Thread.CurrentThread.ManagedThreadId);
            }

            pong.Ping(this);
        }
        public void DetermineApproprateSerialization()
        {
            var a = new Bye();
            var b = new Ping();
            var c = new Pong();
            var d = new DummyMessage();
            var e = new DummyProtoMessage();

            var at = _sh.DetermineApproprateSerialization(a);
            var bt = _sh.DetermineApproprateSerialization(b);
            var ct = _sh.DetermineApproprateSerialization(c);
            var dt = _sh.DetermineApproprateSerialization(d);
            var et = _sh.DetermineApproprateSerialization(e);

            Assert.AreEqual(SerializationType.Manual, at);
            Assert.AreEqual(SerializationType.Manual, bt);
            Assert.AreEqual(SerializationType.Manual, ct);
            Assert.AreEqual(SerializationType.Binary, dt);
            Assert.AreEqual(SerializationType.Protobuf, et);
        }
Exemplo n.º 8
0
        void OnPing(byte[] buf, int size, IPEndPoint remoteEP)
        {
            int offset       = 1;
            var connectionId = BinaryUtil.ReadInt(buf, ref offset);

            if (!m_PeerManager.TryGetValue(connectionId, out var peer))
            {
                return;
            }

            if (!Ping.TryUnpack(buf, size, peer.Encryptor, out var packet))
            {
                return;
            }

            peer.Update(remoteEP, packet.SendSequence, packet.ReceiveSequence);

            offset = new Pong(GetSendId(connectionId), peer).Pack(m_SendBuffer, peer.Encryptor);
            m_Socket.Send(m_SendBuffer, 0, offset, peer.EndPoint);
            Log.Trace("OnPing {0}", connectionId);
        }
Exemplo n.º 9
0
        public void PongSimple3()
        {
            PlayerData p1 = new PlayerData("toto");
            PlayerData p2 = new PlayerData("toto2");

            p1.AddHand(new Tile(Tile.Family.Bamboo, 1));
            p1.AddHand(new Tile(Tile.Family.Bamboo, 1));
            p1.AddHand(new Tile(Tile.Family.Bamboo, 1));

            p2.AddRejected(new Tile(Tile.Family.Bamboo, 1));
            IRule rule = new Pong();

            List <PlayerData> lpd = new List <PlayerData>();

            lpd.Add(p1);
            lpd.Add(p2);

            List <Mahjong.Plugin.IReferee.m_rulepossibility> possi = rule.Execute(lpd, p1);

            Assert.AreEqual(possi.Count, 1);
        }
Exemplo n.º 10
0
        public static bool TryUnpack(byte[] buf, int size, Encryptor encryptor, out Pong packet)
        {
            int offset = 0;

            if (sizeof(byte) + sizeof(int) + sizeof(short) + sizeof(short) > size || buf[offset++] != (byte)Type)
            {
                packet = default;
                return(false);
            }
            if (!encryptor.TryDecrypt(buf, 5, ref size))
            {
                packet = default;
                return(false);
            }
            var id      = BinaryUtil.ReadInt(buf, ref offset);
            var sendSeq = BinaryUtil.ReadShort(buf, ref offset);
            var recvSeq = BinaryUtil.ReadShort(buf, ref offset);

            packet = new Pong(id, sendSeq, recvSeq);
            return(true);
        }
Exemplo n.º 11
0
Arquivo: pong.cs Projeto: KDE/qyoto
    public static int Main(string[] args)
    {
        QCoreApplication app = new QCoreApplication(args);
        if (!QDBusConnection.SessionBus().IsConnected()) {
            Console.Write("Cannot connect to the D-BUS session bus.\n" +
                "To start it, run:\n" +
                "\teval `dbus-launch --auto-syntax`\n");
            return 1;
        }

        if (!QDBusConnection.SessionBus().RegisterService(SERVICE_NAME)) {
            Console.WriteLine(QDBusConnection.SessionBus().LastError().Message());
            return 1;
        }

        Pong pong = new Pong();
        Connect(app, SIGNAL("aboutToQuit()"), pong, SLOT("Terminator()"));
        QDBusConnection.SessionBus().RegisterObject("/", pong, (int) QDBusConnection.RegisterOption.ExportAllSlots);

        return QCoreApplication.Exec();
    }
Exemplo n.º 12
0
        private void ReceiveHead(IAsyncResult ar)
        {
            int count = (int)ar.AsyncState;

            count += socket.EndReceive(ar);
            //如果头数据长度不够,继续读
            if (count < headlen)
            {
                socket.BeginReceive(head, count, headlen - count, SocketFlags.None, new AsyncCallback(ReceiveHead), count);
            }
            else
            {
                //处理一下高低字节位问题
                byte[] realBytesLen = new byte[headlen];
                for (int i = 0; i < headlen; i++)
                {
                    realBytesLen[i] = head[headlen - 1 - i];
                }
                int    length = ByteUtil.byteArray2Int(realBytesLen, 0);
                byte[] data   = new byte[length];//声明接受数组
                count = 0;
                while (count < length)
                {
                    int tempLength = socket.Receive(data, count, length - count, SocketFlags.None);
                    count += tempLength;
                }
                socket.BeginReceive(head, 0, headlen, SocketFlags.None, new AsyncCallback(ReceiveHead), 0);
                MarsMessage msg = ProtobufTool.DeSerialize <MarsMessage>(data);
                //心跳消息直接在本类处理
                if (msg.messageType == 1)
                {
                    Pong pong = ProtobufTool.DeSerialize <Pong>(msg.data);
                    Pong(pong);
                }
                else
                {
                    MessageDispatcher.Receive(msg);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Drone response handler.
        ///
        /// <para>Will listen to the udp packages send from the drone to the receiver and looks up what command it is and react
        /// to it</para>
        /// </summary>
        private void runResponseHandler()
        {
            new Thread(() =>
            {
                // Answer with a Pong
                try
                {
                    using (var udpClient = new UdpClient(devicePort))
                    {
                        LOGGER.Info(String.Format("Listing for response on port %s", devicePort));

                        while (listenToResponse)
                        {
                            byte[] packet = udpClient.Receive(ref SumoRemote);;


                            //LOGGER.trace("Receiving packet {}", convertAndCutPacket(packet, false));

                            commonEventListeners.Where(e => e.test(packet)).ToList().ForEach(e => e.consume(packet));

                            // Answer with a Pong
                            if (packet[0] == 4 || packet[0] == 2)
                            {
                                sendCommand(Pong.pong(packet[2]));

                                continue;
                            }

                            eventListeners.Where(e => e.test(packet)).ToList().ForEach(e => e.consume(packet));
                        }
                    }
                }
                catch (IOException)
                {
                    LOGGER.Warn("Error occurred while receiving packets from the drone.");
                }
            }).Start();
        }
Exemplo n.º 14
0
            public static void Test()
            {
                var system   = new ActorSystem();
                var pingPong = new CountdownEvent(PingPongCount);

                var bruce = new Bruce(pingPong);
                var lee   = new Lee(pingPong);

                system.Add(bruce, ctx => { ctx.Actor.Bus = ctx.Bus; });
                system.Add(lee, ctx => { ctx.Actor.Bus = ctx.Bus; });

                var c = system.Start();

                var p = new Pong();

                c.Publish(ref p);

                var ended = pingPong.Wait(TimeSpan.FromSeconds(10));

                c.Stop();

                Assert.True(ended, "Bruce/Lee didn't ping/pong");
            }
Exemplo n.º 15
0
        public async Task ReceiveAsync(IContext context)
        {
            switch (context.Message)
            {
            case Started _:
                Logger.LogDebug("{Context}", context.Self);
                break;

            case ClusterInit init:
                _identity = init.Identity;
                _initKind = init.Kind;
                break;

            case Ping ping:
                var pong = new Pong {
                    Message = ping.Message, Kind = _initKind ?? "", Identity = _identity ?? ""
                };
                Logger.LogDebug("Received Ping, replying Pong: {@Pong}", pong);
                context.Respond(pong);
                break;

            case SlowPing ping:
                await Task.Delay(ping.DelayMs);

                var slowPong = new Pong {
                    Message = ping.Message, Kind = _initKind ?? "", Identity = _identity ?? ""
                };
                Logger.LogDebug("Received SlowPing, replying Pong after {Delay} ms: {@Pong}", ping.DelayMs, slowPong);
                context.Respond(slowPong);
                break;

            case WhereAreYou hi:
                Logger.LogDebug("Responding to location request");
                context.Respond(new HereIAm {
                    Address = context.Self !.Address, RequestId = hi.RequestId
                });
                break;
Exemplo n.º 16
0
 private void ProcessMessage(IServer server, ISession session, object message)
 {
     if (message is Ping)
     {
         Pong poing = new Pong();
         poing.NodeID     = ID;
         poing.Properties = GetResourceStatistics();
         server.Send(poing, session);
     }
     else if (message is BroadSubscriber)
     {
         BroadSubscriber bs = (BroadSubscriber)message;
         RegisterRemoteSubscribers(bs.NodeID, bs.Name);
         Loger.Process(LogType.DEBUG, "registered remote subscriber [{0}]", bs.Name);
     }
     else if (message is GetSubscribers)
     {
         GetSubscribersResponse response = new GetSubscribersResponse();
         response.NodeID      = ID;
         response.Subscribers = mLocalSubscriberCenter.GetAll();
         server.Send(response, session);
     }
     else if (message is BroadRemoveSubscriber)
     {
         BroadRemoveSubscriber remove = (BroadRemoveSubscriber)message;
         UnRegisterRemoteSubscribers(remove.Name);
     }
     else if (message is Message)
     {
         ((Message)message).Track("node receive message");
         Publish((Message)message);
         ((Message)message).EndTrack("node receive message completed!", this);
     }
     else
     {
     }
 }
Exemplo n.º 17
0
    public void  HandleKey(ConsoleKeyInfo?cki2)
    {
        ConsoleKeyInfo cki = (ConsoleKeyInfo)cki2;

        if (cki.Key == ConsoleKey.D1)
        {
            Hide();
            Snake snake = new Snake(this);
            return;
        }
        else if (cki.Key == ConsoleKey.D2)
        {
            Hide();
            Tetris tetris = new Tetris();
            return;
        }
        else if (cki.Key == ConsoleKey.D3)
        {
            Hide();
            Pong pong = new Pong(true);
            return;
        }
        else if (cki.Key == ConsoleKey.D4)
        {
            Hide();
            Pong pong = new Pong(false);
            return;
        }
        else if (cki.Key == ConsoleKey.D5)
        {
        }
        else if (cki.Key == ConsoleKey.Q)
        {
            Environment.Exit(0);
        }
        getKey();
    }
Exemplo n.º 18
0
        public static void test(string apiKey)
        {
            Console.WriteLine("Testing basic connectivity...");
            Pong pong = ES.testPing(apiKey);

            Console.WriteLine("Message from server: " + pong.message);
            FileStream file = getTestPdfFile();

            Console.WriteLine("Testing file transfer...");
            Byte[] bytes = new byte[file.Length];
            file.Read(bytes, 0, bytes.Length);
            Byte[] rbytes = ES.testEchoFile(apiKey, bytes);

            bool resultOk = true;

            if (bytes.Length == rbytes.Length)
            {
                int i = bytes.Length;
                while (--i >= 0)
                {
                    if (bytes[i] != rbytes[i])
                    {
                        resultOk = false;
                        break;
                    }
                }
            }
            if (resultOk)
            {
                Console.WriteLine("Woohoo!  Everything seems to work.");
            }
            else
            {
                Console.WriteLine("ERROR:  Some kind of problem with file transfer, it seems.");
            }
        }
Exemplo n.º 19
0
        public static PlayState CreateLocalMultiPlayerGame(Game game)
        {
            Pong gameRef = (Pong)game;

            return(new PlayState(game, new HumanPlayer(gameRef.Settings.player1Up, gameRef.Settings.player1Down), new HumanPlayer(gameRef.Settings.player2Up, gameRef.Settings.player2Down)));
        }
Exemplo n.º 20
0
        public static PlayState CreateSinglePlayerGame(Game game)
        {
            Pong gameRef = (Pong)game;

            return(new PlayState(game, new HumanPlayer(gameRef.Settings.player1Up, gameRef.Settings.player1Down), new AIPlayer()));
        }
Exemplo n.º 21
0
    public static int Main(string[] args)
    {
        QCoreApplication app = new QCoreApplication(args);

        QObject obj = new QObject();
        Pong pong = new Pong(obj);
        pong.Connect(app, SIGNAL("aboutToQuit()"), SIGNAL("aboutToQuit()"));
        pong.value = "initial value";
        QDBusConnection.SessionBus().RegisterObject("/", obj);

        if (!QDBusConnection.SessionBus().RegisterService(SERVICE_NAME)) {
            Console.Error.WriteLine(QDBusConnection.SessionBus().LastError().Message());
            return(1);
        }

        return QCoreApplication.Exec();
    }
Exemplo n.º 22
0
 private void InvokePong(Pong packet)
 {
     packetListener.OnPong(packet);
 }
Exemplo n.º 23
0
			private void HandlePong(Pong pong)
			{
				Ponged.Complete(pong);
			}
Exemplo n.º 24
0
 public void SetPong(Pong pong, MyClientMessage message)
 => message.Pong = pong;
Exemplo n.º 25
0
 static void Main()
 {
     Pong game = new Pong();
     game.Run();
 }
Exemplo n.º 26
0
        private void readIncomingCommunication(string msg)
        {
            mutex.WaitOne();

            var data = (JObject)JsonConvert.DeserializeObject(msg);

            Console.WriteLine(data["type"]);
            string type = data["type"].Value <string>();

            MemoryStream stream = GenerateStreamFromString(msg);

            stream.Position = 0;

            // TODO : faire vérification si communication est bien formée

            // vérifier type message
            if (type.Contains(ECommunicationType.HELLO))
            {
                Hello       receivedHello = new Hello();
                List <Peer> listeNoeudsVoisins;
                if (type == ECommunicationType.HELLO_A)
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Hello_A));
                    receivedHello      = (Hello_A)ser.ReadObject(stream);
                    listeNoeudsVoisins = receivedHello.pairs;

                    // si hello qui quelqu'un m'a envoyé, vérifier qu'il n'a pas été déjà reçu à moins de 10 sec
                    // si non, répondre le hello reçu avec la liste noeuds
                    //List<Peer> liste = helloSenders.Where(p => (p.Key.addr == receivedHello.addr_source)).Select(p => p.Key).ToList();
                    if (chatUDPController.isANewReceivedHello(receivedHello, type) /*liste.Count == 0*/)
                    {
                        //List<Peer> listeNoeudsVoisins = receivedHello.pairs;

                        /*if (receivedHello.GetType() == typeof(Hello_A))
                         * {*/
                        Hello_R hello_r   = new Hello_R(myAddress, myPort, chatUDPController.MyNodes);
                        Peer    peer_dest = new Peer(receivedHello.addr_source, receivedHello.port_source);
                        //chatUDPController.helloSenders.Add(peer_dest, DateTime.Now);
                        chatUDPController.receivedHelloAList.Add(peer_dest, DateTime.Now);
                        chatUDPController.sendHello(hello_r, peer_dest);

                        // A TRAITER : Sauf si un noeuds fait un HELLO avec une liste de paire vide (isolé) auquel cas on le rajoute automatiquement
                        // si source contient que moi dans sa liste de noeuds, l'ajouter à ma liste de noeuds (même que ça dépasse 4)
                        // si aucun noeud voisin ou 1 seul et moi même
                        chatUDPController.addPeerToCurrentNeighbors(peer_dest, listeNoeudsVoisins.Count == 0 || (listeNoeudsVoisins.Count == 1 && listeNoeudsVoisins[0].addr.Equals(myAddress) && listeNoeudsVoisins[0].port == myPort));

                        /*if ((listeNoeudsVoisins.Count == 0
                        || (listeNoeudsVoisins.Count == 1 && listeNoeudsVoisins[0].addr == myAddress)) /*listeNoeudsVoisins.Where(p => (p.addr == adresse)).ToList().Count > 0)*
                        ||  && !chatUDPController.myNodes.Contains(peer_dest))
                        || {
                        ||  chatUDPController.myNodes.Add(peer_dest);
                        || }*/
                        //}

                        // récuperer sa liste de noeuds et ajouter à la sienne
                        //fillNeighbours(listeNoeudsVoisins, type);
                        listeNoeudsVoisins.ForEach(p => chatUDPController.addPeerToCurrentNeighbors(p, false));
                    }
                }
                else if (type == ECommunicationType.HELLO_R)
                {
                    if (chatUDPController.isANewReceivedHello(receivedHello, type))
                    {
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Hello_R));
                        receivedHello      = (Hello_R)ser.ReadObject(stream);
                        listeNoeudsVoisins = receivedHello.pairs;

                        Peer peer_dest = new Peer(receivedHello.addr_source, receivedHello.port_source);
                        chatUDPController.receivedHelloRList.Add(peer_dest, DateTime.Now);
                        //chatUDPController.addPeerToCurrentNeighbors(peer_dest, listeNoeudsVoisins.Count == 0 || (listeNoeudsVoisins.Count == 1 && listeNoeudsVoisins[0].addr == myAddress));

                        // récuperer sa liste de noeuds et ajouter à la sienne
                        //fillNeighbours(listeNoeudsVoisins, type);
                        listeNoeudsVoisins.ForEach(p => chatUDPController.addPeerToCurrentNeighbors(p, false));
                    }
                }
            }
            else if (type == ECommunicationType.MESSAGE)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Message));
                Message message = (Message)ser.ReadObject(stream);

                // vérifier si message pas encore reçu
                if (chatUDPController.isANewReceivedMessage(message) /*sentAndReceivedMessages.Where(m => m == message.hash).ToList().Count == 0*/)
                {
                    treatReceivedMessage(message);
                }
            }
            else if (type == ECommunicationType.PING)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Ping));
                Ping ping = (Ping)ser.ReadObject(stream);
                chatUDPController.sendPong(ping.addr_source, ping.port_source);
            }
            else if (type == ECommunicationType.PONG)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Pong));
                Pong pong = (Pong)ser.ReadObject(stream);
                //chatUDPController.receivedPongs.Add(pong);
                if (chatUDPController.SentPings.ContainsKey(pong.addr_source + pong.port_source))
                {
                    chatUDPController.SentPings[pong.addr_source + pong.port_source] = true;
                }
                // TODO : ajouter réponse pong à ping correspondant

                /*if (chatUDPController.dictPingPong.ContainsKey(pong.addr_source + pong.port_source))
                 * {
                 *  chatUDPController.dictPingPong.Remove(pong.addr_source + pong.port_source);
                 * }*/
                // chatUDPController.
            }
            else if (type == ECommunicationType.GOODBYE)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Goodbye));
                Goodbye goodbye = (Goodbye)ser.ReadObject(stream);

                // vérifier si goodbye pas encore reçu
                if (chatUDPController.isANewReceivedGoodbye(goodbye) /*sentAndReceivedMessages.Where(m => m == message.hash).ToList().Count == 0*/)
                {
                    chatUDPController.sentAndReceivedGoodbyes.Add(goodbye.nickname);
                    chatUDPController.sendReceivedGoodbye(goodbye);
                }
            }
            else
            {
                Console.WriteLine("Default case");
            }

            mutex.ReleaseMutex();
        }
Exemplo n.º 27
0
        void Receive_Ping(G2ReceivedPacket packet)
        {
            Core.ServiceBandwidth[Core.DhtServiceID].InPerSec += packet.Root.Data.Length;

            Ping ping = Ping.Decode(packet);

            bool lanIP = Utilities.IsLocalIP(packet.Source.IP);
            bool validSource = (!lanIP || LanMode && lanIP);

            // set local IP
            SetLocalIP(ping.RemoteIP, packet);

            // check loop back
            if (ping.Source != null && Local.Equals(ping.Source))
            {
                if (packet.ReceivedTcp)
                    packet.Tcp.CleanClose("Loopback connection");

                return;
            }

            // dont send back pong if received tunneled and no longer need to use lookup proxies
            // remote would only send tunneled ping if UseGlobalProxies published info on network
            // let our lookup address expire from remote's routing table
            if (packet.Tunneled && !UseLookupProxies)
                return;

            // setup pong reply
            Pong pong = new Pong();

            if (ping.Source != null)
                pong.Source = GetLocalSource();

            if (ping.RemoteIP != null)
                pong.RemoteIP = packet.Source.IP;

            if (!IsLookup && Core.Context.SignedUpdate != null && Core.Context.SignedUpdate.Loaded)
                pong.Version = Core.Context.SignedUpdate.SequentialVersion;

            int sentBytes = 0;

            // received tcp
            if (packet.ReceivedTcp)
            {
                if (ping.Source == null)
                {
                    packet.Tcp.SendPacket(pong);
                    return;
                }

                if (validSource)
                {
                    if (ping.Source.Firewall == FirewallType.Open)
                        Routing.Add(new DhtContact(ping.Source, packet.Source.IP));

                    // received incoming tcp means we are not firewalled
                    if (!packet.Tcp.Outbound)
                    {
                        // done here to prevent setting open for loopback tcp connection
                        Core.SetFirewallType(FirewallType.Open);
                        pong.Source.Firewall = FirewallType.Open;
                    }
                }

                // check if already connected
                if (packet.Tcp.Proxy == ProxyType.Unset && TcpControl.GetProxy(ping.Source) != null)
                {
                    packet.Tcp.CleanClose("Dupelicate Connection");
                    return;
                }

                packet.Tcp.UserID = ping.Source.UserID;
                packet.Tcp.ClientID = ping.Source.ClientID;
                packet.Tcp.TcpPort = ping.Source.TcpPort;
                packet.Tcp.UdpPort = ping.Source.UdpPort;

                // if inbound connection, to our open host, and haven't checked fw yet
                if (!packet.Tcp.Outbound &&
                    ping.Source.Firewall != FirewallType.Open &&
                    !packet.Tcp.CheckedFirewall)
                {
                    TcpControl.MakeOutbound(packet.Source, ping.Source.TcpPort, "check firewall");
                    packet.Tcp.CheckedFirewall = true;
                }

                pong.Direct = true;
                sentBytes = packet.Tcp.SendPacket(pong);

                // dont send close if proxies maxxed yet, because their id might be closer than current proxies
            }

            // ping received udp or tunneled
            else
            {
                if (validSource)
                {
                    // received udp traffic, we must be behind a NAT at least
                    if (Core.Firewall == FirewallType.Blocked && !packet.Tunneled)
                        Core.SetFirewallType(FirewallType.NAT);

                    Routing.TryAdd(packet, ping.Source);
                }

                // if received over lan, the port isn't set
                if (packet.Source.UdpPort == 0)
                    packet.Source.UdpPort = ping.Source.UdpPort;

                // send pong
                sentBytes = SendPacket(packet.Source, pong);
            }

            Core.ServiceBandwidth[Core.DhtServiceID].OutPerSec += sentBytes;
        }
Exemplo n.º 28
0
 private void HandleInternal(Pong msg)
 {
     Console.WriteLine("Received a pong");
 }
Exemplo n.º 29
0
        /// <summary>
        /// Receive web socket result
        /// </summary>
        /// <param name="buffer">The buffer to copy data into</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The web socket result details</returns>
        public override async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken)
        {
            try
            {
                // we may receive control frames so reading needs to happen in an infinite loop
                while (true)
                {
                    // allow this operation to be cancelled from iniside OR outside this instance
                    using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalReadCts.Token, cancellationToken))
                    {
                        WebSocketFrame frame = null;
                        try
                        {
                            frame = await WebSocketFrameReader.ReadAsync(_stream, buffer, linkedCts.Token);

                            Events.Log.ReceivedFrame(_guid, frame.OpCode, frame.IsFinBitSet, frame.Count);
                        }
                        catch (SocketException)
                        {
                            // do nothing, the socket has been disconnected
                        }
                        catch (InternalBufferOverflowException ex)
                        {
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.MessageTooBig, "Frame too large to fit in buffer. Use message fragmentation", ex);

                            throw;
                        }
                        catch (ArgumentOutOfRangeException ex)
                        {
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, "Payload length out of range", ex);

                            throw;
                        }
                        catch (EndOfStreamException ex)
                        {
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InvalidPayloadData, "Unexpected end of stream encountered", ex);

                            throw;
                        }
                        catch (OperationCanceledException ex)
                        {
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.EndpointUnavailable, "Operation cancelled", ex);

                            throw;
                        }
                        catch (Exception ex)
                        {
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Error reading WebSocket frame", ex);

                            throw;
                        }

                        switch (frame.OpCode)
                        {
                        case WebSocketOpCode.ConnectionClose:
                            return(await RespondToCloseFrame(frame, buffer, linkedCts.Token));

                        case WebSocketOpCode.Ping:
                            ArraySegment <byte> pingPayload = new ArraySegment <byte>(buffer.Array, buffer.Offset, frame.Count);
                            await SendPongAsync(pingPayload, linkedCts.Token);

                            break;

                        case WebSocketOpCode.Pong:
                            ArraySegment <byte> pongBuffer = new ArraySegment <byte>(buffer.Array, frame.Count, buffer.Offset);
                            Pong?.Invoke(this, new PongEventArgs(pongBuffer));
                            break;

                        case WebSocketOpCode.TextFrame:
                            if (!frame.IsFinBitSet)
                            {
                                // continuation frames will follow, record the message type Text
                                _continuationFrameMessageType = WebSocketMessageType.Text;
                            }
                            return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Text, frame.IsFinBitSet));

                        case WebSocketOpCode.BinaryFrame:
                            if (!frame.IsFinBitSet)
                            {
                                // continuation frames will follow, record the message type Binary
                                _continuationFrameMessageType = WebSocketMessageType.Binary;
                            }
                            return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Binary, frame.IsFinBitSet));

                        case WebSocketOpCode.ContinuationFrame:
                            return(new WebSocketReceiveResult(frame.Count, _continuationFrameMessageType, frame.IsFinBitSet));

                        default:
                            Exception ex = new NotSupportedException($"Unknown WebSocket opcode {frame.OpCode}");
                            await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, ex.Message, ex);

                            throw ex;
                        }
                    }
                }
            }
            catch (Exception catchAll)
            {
                // Most exceptions will be caught closer to their source to send an appropriate close message (and set the WebSocketState)
                // However, if an unhandled exception is encountered and a close message not sent then send one here
                if (_state == WebSocketState.Open)
                {
                    await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Unexpected error reading from WebSocket", catchAll);
                }

                throw;
            }
        }
Exemplo n.º 30
0
 public void Pong(Pong pong)
 {
     _queue.Enqueue(() => Consume(pong));
 }
Exemplo n.º 31
0
        private void Initialize(string uri, string subProtocol, List <KeyValuePair <string, string> > cookies, List <KeyValuePair <string, string> > customHeaderItems, string userAgent, string origin, WebSocketVersion version, EndPoint httpConnectProxy, int receiveBufferSize)
        {
            if (version == WebSocketVersion.None)
            {
                NotSpecifiedVersion = true;
                version             = WebSocketVersion.Rfc6455;
            }
            Version           = version;
            ProtocolProcessor = GetProtocolProcessor(version);
            Cookies           = cookies;
            Origin            = origin;
            if (!string.IsNullOrEmpty(userAgent))
            {
                if (customHeaderItems == null)
                {
                    customHeaderItems = new List <KeyValuePair <string, string> >();
                }
                customHeaderItems.Add(new KeyValuePair <string, string>("User-Agent", userAgent));
            }
            if (customHeaderItems != null && customHeaderItems.Count > 0)
            {
                CustomHeaderItems = customHeaderItems;
            }
            Handshake handshake = new Handshake();

            m_CommandDict.Add(handshake.Name, handshake);
            Text text = new Text();

            m_CommandDict.Add(text.Name, text);
            Binary binary = new Binary();

            m_CommandDict.Add(binary.Name, binary);
            Close close = new Close();

            m_CommandDict.Add(close.Name, close);
            Ping ping = new Ping();

            m_CommandDict.Add(ping.Name, ping);
            Pong pong = new Pong();

            m_CommandDict.Add(pong.Name, pong);
            BadRequest badRequest = new BadRequest();

            m_CommandDict.Add(badRequest.Name, badRequest);
            m_StateCode        = -1;
            SubProtocol        = subProtocol;
            Items              = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            m_HttpConnectProxy = httpConnectProxy;
            TcpClientSession tcpClientSession;

            if (uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
            {
                tcpClientSession = CreateClient(uri);
            }
            else
            {
                if (!uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("Invalid uri", "uri");
                }
                tcpClientSession = CreateSecureClient(uri);
            }
            tcpClientSession.ReceiveBufferSize = ((receiveBufferSize > 0) ? receiveBufferSize : 4096);
            tcpClientSession.Connected        += client_Connected;
            tcpClientSession.Closed           += client_Closed;
            tcpClientSession.Error            += client_Error;
            tcpClientSession.DataReceived     += client_DataReceived;
            Client             = tcpClientSession;
            EnableAutoSendPing = true;
        }
Exemplo n.º 32
0
 public void Pong(Pong pong)
 {
     _fiber.Add(() => Consume(pong));
 }
Exemplo n.º 33
0
		public void Pong(Pong pong)
		{
			_fiber.Add(() => Consume(pong));
		}
Exemplo n.º 34
0
 public BaseGameState(Game game) : base(game)
 {
     GameRef = (Pong)game;
 }
Exemplo n.º 35
0
 /// <summary>
 /// Called when a Pong frame is received
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnPong(PongEventArgs e)
 {
     Pong?.Invoke(this, e);
 }
Exemplo n.º 36
0
 static void Main()
 {
     Pong pong = new Pong();
     Game g    = new Game();
 }
Exemplo n.º 37
0
 static void Main()
 {
     using (var game = new Pong())
         game.Run();
 }
Exemplo n.º 38
0
        private async Task ProcessMessageAsync <T>(
            Blockchain <T> blockchain,
            Message message,
            CancellationToken cancellationToken)
            where T : IAction
        {
            switch (message)
            {
            case Ping ping:
            {
                _logger.Debug($"Ping received.");
                var reply = new Pong
                {
                    Identity = ping.Identity,
                };
                await ReplyAsync(reply, cancellationToken);

                break;
            }

            case Messages.PeerSetDelta peerSetDelta:
            {
                _deltas.Enqueue(peerSetDelta.Delta);
                break;
            }

            case GetBlockHashes getBlockHashes:
            {
                IEnumerable <HashDigest <SHA256> > hashes =
                    blockchain.FindNextHashes(
                        getBlockHashes.Locator,
                        getBlockHashes.Stop,
                        500);
                var reply = new BlockHashes(hashes)
                {
                    Identity = getBlockHashes.Identity,
                };
                await ReplyAsync(reply, cancellationToken);

                break;
            }

            case GetBlocks getBlocks:
            {
                await TransferBlocks(
                    blockchain, getBlocks, cancellationToken);

                break;
            }

            case GetTxs getTxs:
            {
                await TransferTxs(
                    blockchain, getTxs, cancellationToken);

                break;
            }

            case TxIds txIds:
            {
                await ProcessTxIds(
                    txIds, blockchain, cancellationToken);

                break;
            }

            default:
                Trace.Fail($"Can't handle message. [{message}]");
                break;
            }
        }
Exemplo n.º 39
0
        public void isPing_NumDivBy5_Pong()
        {
            Pong testPingPong = new Pong();

            Assert.AreEqual("Ping", testPingPong.GetPong(3));
        }
Exemplo n.º 40
0
		public void Run()
		{
			Stopwatch timer = Stopwatch.StartNew();

			const int actorCount = 20;
			const int pingCount = 4000;

			var actors = new ActorInstance[actorCount + 1];

			var complete = new Future<int>();

			var latch = new CountdownLatch(actorCount * pingCount, complete.Complete);

			for (int i = actorCount; i >= 0; i--)
			{
				actors[i] = AnonymousActor.New(inbox =>
					{
						var pong = new Pong();

						var server = actors[(i + 1)];

						inbox.Loop(loop =>
							{
								loop.Receive<Request<Ping>>(request =>
									{
										request.Respond(pong);
										loop.Continue();
									});
							});


						if (i < actorCount)
						{
							var ping = new Ping();
							int count = 0;

							Action loop = null;
							loop = () =>
								{
									server.Request(ping, inbox)
										.Receive<Response<Pong>>(response =>
											{
												latch.CountDown();
												count++;
												if (count < pingCount)
													loop();
											});
								};

							loop();
						}
					});
			}

			bool completed = complete.WaitUntilCompleted(5.Minutes());

			timer.Stop();

			for (int i = 0; i < actorCount; i++)
			{
				actors[i].Exit();
				actors[i] = null;
			}

			if (!completed)
			{
				Console.WriteLine("Process did not complete");
				return;
			}

			Console.WriteLine("Processed {0} messages in with {1} actors in {2}ms", pingCount, actorCount, timer.ElapsedMilliseconds);

			Console.WriteLine("That's {0} messages per second!", ((long)pingCount * actorCount * 2 * 1000) / timer.ElapsedMilliseconds);
		}
Exemplo n.º 41
0
        private void ProcessMessageHandler(object target, Message message)
        {
            switch (message)
            {
            case Ping ping:
            {
                _logger.Debug($"Received a {nameof(Ping)} message.");

                // This case can be dealt in Transport.
                var pong = new Pong()
                {
                    Identity = ping.Identity,
                };

                Transport.ReplyMessage(pong);
                break;
            }

            case GetChainStatus getChainStatus:
            {
                _logger.Debug($"Received a {nameof(GetChainStatus)} message.");

                // This is based on the assumption that genesis block always exists.
                var chainStatus = new ChainStatus(
                    BlockChain.Genesis.Hash,
                    BlockChain.Tip.Index,
                    BlockChain.Tip.TotalDifficulty)
                {
                    Identity = getChainStatus.Identity,
                };

                Transport.ReplyMessage(chainStatus);
                break;
            }

            case FindNeighbors _:
                _logger.Debug($"Received a {nameof(FindNeighbors)} message.");
                break;

            case GetBlockHashes getBlockHashes:
            {
                BlockChain.FindNextHashes(
                    getBlockHashes.Locator,
                    getBlockHashes.Stop,
                    FindNextHashesChunkSize
                    ).Deconstruct(
                    out long?offset,
                    out IReadOnlyList <HashDigest <SHA256> > hashes
                    );
                var reply = new BlockHashes(offset, hashes)
                {
                    Identity = getBlockHashes.Identity,
                };
                Transport.ReplyMessage(reply);
                break;
            }

            case GetRecentStates getRecentStates:
                TransferRecentStates(getRecentStates);
                break;

            case GetBlocks getBlocks:
                TransferBlocks(getBlocks);
                break;

            case GetTxs getTxs:
                TransferTxs(getTxs);
                break;

            case TxIds txIds:
                ProcessTxIds(txIds);
                break;

            case BlockHashes _:
                _logger.Error($"{nameof(BlockHashes)} messages are only for IBD.");
                break;

            case BlockHeaderMessage blockHeader:
                Task.Run(
                    async() => await ProcessBlockHeader(blockHeader, _cancellationToken),
                    _cancellationToken
                    );
                break;

            case GetBlockStates getBlockStates:
                TransferBlockStates(getBlockStates);
                break;

            default:
                throw new InvalidMessageException(
                          $"Failed to handle message: {message}",
                          message
                          );
            }
        }
Exemplo n.º 42
0
    static void Main()
    {
        Pong game = new Pong();

        game.Run();
    }
Exemplo n.º 43
-1
        public override void Draw(float dt)
        {
            base.Draw(dt);

            var g = Game.Inst.Graphics;

            var fadeVal = Math.Min(0.5f * m_Time * m_Time, 1.0f);

            Pong.PsChromaticAberration.SetConstants(0.85f * fadeVal);
            Pong.PsBlend.SetConstants(fadeVal * fadeVal);
            Pong.PsNoise.SetConstants(Pong.Rnd(1, 999));

            g.BeginFrame();

            if (m_Time < 3.0f)
            {
                g.RenderTarget = Pong.RenderTargets[0];
                g.PixelShader  = g.DefaultPixelShader;
                g.PixelShader.SetTextures(Pong.TexSplash);

                g.DrawTriMesh(Pong.TmUnitQuad, Matrix4x4.Identity());
                g.ApplyPostFX(Pong.RenderTargets[0], Pong.PsChromaticAberration);
            }
            else
            {
                Pong.PsBlend.SetConstants(0.86f);
            }

            g.ApplyPostFX(Pong.RenderTargets[0], Pong.PsBlend);
            g.ApplyPostFX(Pong.RenderTargets[0], Pong.PsSoft);
            g.ApplyPostFX(g.ScreenRenderTarget, Pong.PsNoise);

            g.EndFrame();

            m_Time += dt;

            if (m_Time > 3.5f)
            {
                Game.Inst.LeaveScene();
                Game.Inst.EnterScene(new PlayingScene());
            }
        }