Пример #1
0
        static void Main(string[] args)
        {
            EventBasedNetListener      netListener      = new EventBasedNetListener();
            EventBasedNatPunchListener netPunchListener = new EventBasedNatPunchListener();

            NetManager client = new NetManager(netListener);
            NetPeer    peer   = null;

            netPunchListener.NatIntroductionRequest += NetPunchListener_NatIntroductionRequest1;

            //收到这个消息说明通道已经打通
            netPunchListener.NatIntroductionSuccess += (point, token) =>
            {
                peer = client.Connect(point, ConnectionKey);//peer必须马上用 否则就没了?
                Console.WriteLine("Success . Connecting to : {0}, connection created: {1}", point, peer != null);
                //peer.Send(Encoding.UTF8.GetBytes("hello1"), DeliveryMethod.ReliableOrdered);
            };


            netListener.NetworkReceiveEvent += NetListener_NetworkReceiveEvent;
            netListener.PeerConnectedEvent  += NetListener_PeerConnectedEvent;

            //netListener.PeerConnectedEvent += peer =>
            //{
            //    Console.WriteLine("PeerConnected: " + peer.EndPoint.ToString());
            //};

            //netListener.NetworkReceiveEvent += NetListener_NetworkReceiveEvent;
            netListener.ConnectionRequestEvent += request =>
            {
                request.AcceptIfKey(ConnectionKey);//关键方法
                Console.WriteLine("acceptifkey: connectionkey");
            };

            netListener.PeerDisconnectedEvent += (p, disconnectInfo) =>
            {
                Console.WriteLine("PeerDisconnected: " + disconnectInfo.Reason);
                if (disconnectInfo.AdditionalData.AvailableBytes > 0)
                {
                    Console.WriteLine("Disconnect data: " + disconnectInfo.AdditionalData.GetInt());
                }
            };

            client.NatPunchEnabled = true;
            client.NatPunchModule.Init(netPunchListener);
            //client.LocalPort;
            client.Start();
            client.NatPunchModule.SendNatIntroduceRequest(NetUtils.MakeEndPoint("2017studio.imwork.net", ServerPort), "token2", hostByte);
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    var key = Console.ReadKey(true).Key;
                    if (key == ConsoleKey.Escape)
                    {
                        break;
                    }
                    if (key == ConsoleKey.A)
                    {
                        //NetDataWriter ndw = new NetDataWriter();

                        //peer.Send()
                        //peer.Send();
                        NetDataWriter ndw = new NetDataWriter();
                        ndw.Put("hello,im" + netListener.GetHashCode());
                        ndw.Put(new byte[2000]);
                        peer.Send(ndw, DeliveryMethod.ReliableOrdered);
                        //client.SendToAll(Encoding.ASCII.GetBytes("hello,im" + netListener.GetHashCode()), DeliveryMethod.ReliableOrdered);
                    }
                }
                client.NatPunchModule.PollEvents();
                client.PollEvents();
                Thread.Sleep(10);
            }
            Console.WriteLine("Hello World!");
        }
Пример #2
0
        public void Run()
        {
            Console.WriteLine("=== HolePunch Test ===");

            EventBasedNetListener      netListener       = new EventBasedNetListener();
            EventBasedNatPunchListener natPunchListener1 = new EventBasedNatPunchListener();
            EventBasedNatPunchListener natPunchListener2 = new EventBasedNatPunchListener();

            netListener.PeerConnectedEvent += peer =>
            {
                Console.WriteLine("PeerConnected: " + peer.EndPoint.ToString());
            };

            netListener.ConnectionRequestEvent += request =>
            {
                request.AcceptIfKey(ConnectionKey);
            };

            netListener.PeerDisconnectedEvent += (peer, disconnectInfo) =>
            {
                Console.WriteLine("PeerDisconnected: " + disconnectInfo.Reason);
                if (disconnectInfo.AdditionalData.AvailableBytes > 0)
                {
                    Console.WriteLine("Disconnect data: " + disconnectInfo.AdditionalData.GetInt());
                }
            };

            natPunchListener1.NatIntroductionSuccess += (point, token) =>
            {
                var peer = _c1.Connect(point, ConnectionKey);
                Console.WriteLine("Success C1. Connecting to C2: {0}, connection created: {1}", point, peer != null);
            };

            natPunchListener2.NatIntroductionSuccess += (point, token) =>
            {
                var peer = _c2.Connect(point, ConnectionKey);
                Console.WriteLine("Success C2. Connecting to C1: {0}, connection created: {1}", point, peer != null);
            };

            _c1 = new NetManager(netListener);
            _c1.NatPunchEnabled = true;
            _c1.NatPunchModule.Init(natPunchListener1);
            _c1.Start();

            _c2 = new NetManager(netListener);
            _c2.NatPunchEnabled = true;
            _c2.NatPunchModule.Init(natPunchListener2);
            _c2.Start();

            _puncher = new NetManager(netListener);
            _puncher.Start(ServerPort);
            _puncher.NatPunchEnabled = true;
            _puncher.NatPunchModule.Init(this);

            _c1.NatPunchModule.SendNatIntroduceRequest(NetUtils.MakeEndPoint("::1", ServerPort), "token1");
            _c2.NatPunchModule.SendNatIntroduceRequest(NetUtils.MakeEndPoint("::1", ServerPort), "token1");

            // keep going until ESCAPE is pressed
            Console.WriteLine("Press ESC to quit");

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    var key = Console.ReadKey(true).Key;
                    if (key == ConsoleKey.Escape)
                    {
                        break;
                    }
                    if (key == ConsoleKey.A)
                    {
                        Console.WriteLine("C1 stopped");
                        _c1.DisconnectPeer(_c1.GetFirstPeer(), new byte[] { 1, 2, 3, 4 });
                        _c1.Stop();
                    }
                }

                DateTime nowTime = DateTime.Now;

                _c1.NatPunchModule.PollEvents();
                _c2.NatPunchModule.PollEvents();
                _puncher.NatPunchModule.PollEvents();
                _c1.PollEvents();
                _c2.PollEvents();

                //check old peers
                foreach (var waitPeer in _waitingPeers)
                {
                    if (nowTime - waitPeer.Value.RefreshTime > KickTime)
                    {
                        _peersToRemove.Add(waitPeer.Key);
                    }
                }

                //remove
                for (int i = 0; i < _peersToRemove.Count; i++)
                {
                    Console.WriteLine("Kicking peer: " + _peersToRemove[i]);
                    _waitingPeers.Remove(_peersToRemove[i]);
                }
                _peersToRemove.Clear();

                Thread.Sleep(10);
            }

            _c1.Stop();
            _c2.Stop();
            _puncher.Stop();
        }
Пример #3
0
        public void Run()
        {
            EventBasedNetListener      netListener       = new EventBasedNetListener();
            EventBasedNatPunchListener natPunchListener1 = new EventBasedNatPunchListener();
            EventBasedNatPunchListener natPunchListener2 = new EventBasedNatPunchListener();

            netListener.PeerConnectedEvent += peer =>
            {
                Console.WriteLine("PeerConnected: " + peer.EndPoint.ToString());
            };

            netListener.PeerDisconnectedEvent += (peer, s) =>
            {
                Console.WriteLine("PeerDisconnected: " + s);
            };

            natPunchListener1.NatIntroductionSuccess += (point, token) =>
            {
                Console.WriteLine("Success C1. Connecting to C2");
                //_c1.Connect(point);
            };

            natPunchListener2.NatIntroductionSuccess += (point, token) =>
            {
                Console.WriteLine("Success C2. Connecting to C1");
                _c2.Connect(point);
            };

            _c1 = new NetClient(netListener, "gamekey");
            _c1.PeerToPeerMode  = true;
            _c1.NatPunchEnabled = true;
            _c1.NatPunchModule.Init(natPunchListener1);
            _c1.Start();

            _c2 = new NetClient(netListener, "gamekey");
            _c2.PeerToPeerMode  = true;
            _c2.NatPunchEnabled = true;
            _c2.NatPunchModule.Init(natPunchListener2);
            _c2.Start();

            _puncher = new NetClient(netListener, "notneed");
            _puncher.Start(ServerPort);
            _puncher.NatPunchEnabled = true;
            _puncher.NatPunchModule.Init(this);

            _c1.NatPunchModule.SendNatIntroduceRequest(new NetEndPoint("localhost", ServerPort), "token1");
            _c2.NatPunchModule.SendNatIntroduceRequest(new NetEndPoint("localhost", ServerPort), "token1");

            // keep going until ESCAPE is pressed
            Console.WriteLine("Press ESC to quit");

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    var key = Console.ReadKey().Key;
                    if (key == ConsoleKey.Escape)
                    {
                        break;
                    }
                    else if (key == ConsoleKey.A)
                    {
                        Console.WriteLine("C1 stopped");
                        _c1.Stop();
                    }
                }

                DateTime nowTime = DateTime.Now;

                _c1.NatPunchModule.PollEvents();
                _c2.NatPunchModule.PollEvents();
                _puncher.NatPunchModule.PollEvents();
                _c1.PollEvents();
                _c2.PollEvents();

                //check old peers
                foreach (var waitPeer in _waitingPeers)
                {
                    if (nowTime - waitPeer.Value.RefreshTime > KickTime)
                    {
                        _peersToRemove.Add(waitPeer.Key);
                    }
                }

                //remove
                for (int i = 0; i < _peersToRemove.Count; i++)
                {
                    Console.WriteLine("Kicking peer: " + _peersToRemove[i]);
                    _waitingPeers.Remove(_peersToRemove[i]);
                }
                _peersToRemove.Clear();

                Thread.Sleep(10);
            }

            _c1.Stop();
            _c2.Stop();
            _puncher.Stop();
        }
Пример #4
0
    public void Run(string puncherServerIp)
    {
        Console.WriteLine("=== HolePunch Test ===");

        EventBasedNetListener      clientListener    = new EventBasedNetListener();
        EventBasedNatPunchListener natPunchListener1 = new EventBasedNatPunchListener();

        clientListener.PeerConnectedEvent += peer =>
        {
            Console.WriteLine("PeerConnected: " + peer.EndPoint);
            // Can now persist peer in a list, and use peer.SendWithDeliveryEvent(..)
        };

        clientListener.ConnectionRequestEvent += request =>
        {
            request.AcceptIfKey(ConnectionKey);
        };

        clientListener.PeerDisconnectedEvent += (peer, disconnectInfo) =>
        {
            Console.WriteLine($"PeerDisconnected ({peer.EndPoint}): {disconnectInfo.Reason}");
            if (disconnectInfo.AdditionalData.AvailableBytes > 0)
            {
                Console.WriteLine("Disconnect data: " + disconnectInfo.AdditionalData.GetInt());
            }
        };

        natPunchListener1.NatIntroductionSuccess += (point, addrType, token) =>
        {
            // TODO: Consider handling that if two peers are on the same PC, and using a hole puncher on localhost, two NAT introductions are initiated:
            // One over localhost, and one over LAN

            var peer = _clientNetManager.Connect(point, ConnectionKey);
            Console.WriteLine($"NatIntroductionSuccess. Connecting to other client: {point}, type: {addrType}, connection created: {peer != null}");
            Console.WriteLine($"Received token: {token}");
        };

        _clientNetManager = new NetManager(clientListener)
        {
            IPv6Enabled     = Ipv6Mode,
            NatPunchEnabled = true
        };
        _clientNetManager.NatPunchModule.Init(natPunchListener1);
        _clientNetManager.Start();

        _clientNetManager.NatPunchModule.SendNatIntroduceRequest(puncherServerIp, PuncherServerPort, "token1");

        // keep going until ESCAPE is pressed
        Console.WriteLine("Press ESC to quit");

        while (true)
        {
            if (Console.KeyAvailable)
            {
                var key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.Escape)
                {
                    break;
                }
                if (key == ConsoleKey.A)
                {
                    Console.WriteLine("Client stopped");
                    _clientNetManager.DisconnectPeer(_clientNetManager.FirstPeer, new byte[] { 1, 2, 3, 4 });
                    _clientNetManager.Stop();
                }
            }

            _clientNetManager.NatPunchModule.PollEvents();
            _clientNetManager.PollEvents();

            Thread.Sleep(10);
        }

        _clientNetManager.Stop();
    }
Пример #5
0
        public override void Run()
        {
            var     connected = false;
            NetPeer?peer      = null;

            Console.WriteLine("Stating Client...");
            RequestRelayServerIp();

            var serverIp = RequestServerIp();

            var globalServer = new IPEndPoint(IPAddress.Parse(RelayServerIp), 4240);

            var natPunchListener = new EventBasedNatPunchListener();

            natPunchListener.NatIntroductionSuccess += (point, _, _) =>
            {
                Console.WriteLine("Nat Introduction Success, Connecting to " + point);
                peer      = Net.Connect(point, "CSM");
                connected = true;
            };

            var netListener = new EventBasedNetListener();

            netListener.NetworkReceiveEvent += (peer, reader, method) =>
            {
                var message = reader.GetString();
                Console.WriteLine($"[{peer}] {message}");
            };

            netListener.PeerConnectedEvent += netPeer =>
            {
                Console.WriteLine("Connected to server: " + netPeer.EndPoint);
            };

            netListener.NetworkErrorEvent += (point, error) =>
            {
                Console.WriteLine("Network Error: " + error);
            };

            Net = new NetManager(netListener);
            Net.NatPunchEnabled            = true;
            Net.UnconnectedMessagesEnabled = true;
            Net.NatPunchModule.Init(natPunchListener);

            Net.Start();
            Net.NatPunchModule.SendNatIntroduceRequest(globalServer, $"client_{serverIp}");

            var running = true;

            while (running)
            {
                Net.NatPunchModule.PollEvents();
                Net.PollEvents();

                // Wait till connected
                if (peer == null)
                {
                    Thread.Sleep(100);
                    continue;
                }

                Console.WriteLine("Sending ping:");
                peer.Send(NetDataWriter.FromString("Ping from client"), DeliveryMethod.Unreliable);

                Thread.Sleep(100);
            }

            Net.Stop();
        }
Пример #6
0
        public override void Run()
        {
            Console.WriteLine("Stating Server...");
            RequestRelayServerIp();

            var globalServer = new IPEndPoint(IPAddress.Parse(RelayServerIp), 4240);

            var natPunchListener = new EventBasedNatPunchListener();

            natPunchListener.NatIntroductionSuccess += (point, _, _) =>
            {
                Console.WriteLine("Nat Introduction Success, Accepting connection from " + point);
            };

            var netListener = new EventBasedNetListener();

            netListener.NetworkReceiveEvent += (peer, reader, method) =>
            {
                Console.WriteLine("Server received: " + reader.GetString() + ". Sending pong...");
                peer.Send(NetDataWriter.FromString("Pong from server!"), DeliveryMethod.ReliableOrdered);
            };

            netListener.PeerConnectedEvent += peer =>
            {
                Console.WriteLine("Client connected to server: " + peer.EndPoint);
            };

            netListener.ConnectionRequestEvent += request =>
            {
                Console.WriteLine("Connection request from: " + request.RemoteEndPoint);
                request.AcceptIfKey("CSM");
            };

            netListener.NetworkErrorEvent += (point, error) =>
            {
                Console.WriteLine("Network Error: " + error);
            };

            Net = new NetManager(netListener);
            Net.NatPunchEnabled            = true;
            Net.UnconnectedMessagesEnabled = true;
            Net.NatPunchModule.Init(natPunchListener);

            var success = Net.Start(4230);

            if (!success)
            {
                Console.WriteLine("Could not start server for some reason");
            }

            Net.NatPunchModule.SendNatIntroduceRequest(globalServer, "server_a7Gd3H");

            var running = true;

            while (running)
            {
                Net.NatPunchModule.PollEvents();
                Net.PollEvents();

                // This would be sent every 5 seconds in the actual game
                Net.SendUnconnectedMessage(NetDataWriter.FromString("server_a7Gd3H"), globalServer);

                Thread.Sleep(100);
            }

            Net.Stop();
        }