private void p2pNetwork_OnPeerConnected(PeerToPeerNetwork Listener, PeerConnection Peer)
        {
            IPEndPoint Endpoint = (IPEndPoint)Peer.Tcp.Client.RemoteEndPoint;

#if LineListener
            Console.Out.WriteLine("Receiving connection from " + Endpoint.ToString());
#endif

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.remotePlayerIPs.ContainsKey(Endpoint.Address))
                {
                    Peer.Dispose();
                    return;
                }
            }

            Peer.OnClosed   += new EventHandler(Peer_OnClosed);
            Peer.OnReceived += new BinaryEventHandler(Peer_OnReceived);

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalEndpoint.Address.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Peer.SendTcp(Output.GetPacket());
        }
        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            if (this.p2pNetwork != null)
            {
                this.p2pNetwork.Dispose();
                this.p2pNetwork = null;
            }

            if (this.peersByFullJid != null)
            {
                PeerState[] States;

                lock (this.peersByFullJid)
                {
                    States = new PeerState[this.peersByFullJid.Count];
                    this.peersByFullJid.Values.CopyTo(States, 0);

                    this.peersByFullJid.Clear();
                }

                this.peersByFullJid = null;

                foreach (PeerState State in States)
                {
                    State.ClearCallbacks();
                    State.Close();
                }
            }
        }
示例#3
0
 internal IPEndPoint GetExpectedEndpoint(PeerToPeerNetwork Network)
 {
     if (IPAddress.Equals(this.publicEndpoint.Address, Network.ExternalAddress))
     {
         return(this.localEndpoint);
     }
     else
     {
         return(this.publicEndpoint);
     }
 }
        /// <summary>
        /// Class managing peer-to-peer serveless XMPP communication.
        /// </summary>
        /// <param name="ApplicationName">Name of application, as it will be registered in Internet Gateways.</param>
        /// <param name="BareJid">Bare JID of local end-point.</param>
        /// <param name="LocalPort">Desired local port number. If 0, a dynamic port number will be assigned.</param>
        /// <param name="ExternalPort">Desired external port number. If 0, a dynamic port number will be assigned.</param>
        /// <param name="Backlog">Connection backlog.</param>
        /// <param name="Sniffers">Sniffers</param>
        public XmppServerlessMessaging(string ApplicationName, string BareJid, int LocalPort, int ExternalPort, int Backlog,
                                       params ISniffer[] Sniffers)
            : base(Sniffers)
        {
            this.bareJid    = BareJid;
            this.p2pNetwork = new PeerToPeerNetwork(ApplicationName, LocalPort, ExternalPort, Backlog, Sniffers)
            {
                EncapsulatePackets = false
            };

            // TODO: Implement support for NAT-PMP

            this.p2pNetwork.OnPeerConnected += P2PNetwork_OnPeerConnected;
        }
        private void p2pNetwork_OnUdpDatagramReceived(PeerToPeerNetwork Sender, UdpDatagramEventArgs e)
        {
            Player Player;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.remotePlayersByEndpoint.TryGetValue(e.RemoteEndpoint, out Player))
                {
                    return;
                }
            }

            if (!(Player.Connection is null))
            {
                Player.Connection.UdpDatagramReceived(Sender, e);
            }
        }
        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            this.CloseMqtt();

            this.State = MultiPlayerState.Closed;

            if (!(this.p2pNetwork is null))
            {
                this.p2pNetwork.Dispose();
                this.p2pNetwork = null;
            }

            if (!(this.ready is null))
            {
                this.ready.Close();
                this.ready = null;
            }

            if (!(this.error is null))
            {
                this.error.Close();
                this.error = null;
            }

            if (!(this.remotePlayersByEndpoint is null))
            {
                lock (this.remotePlayersByEndpoint)
                {
                    this.playersById.Clear();
                    this.remotePlayersByIndex.Clear();

                    foreach (Player Player in this.remotePlayersByEndpoint.Values)
                    {
                        if (!(Player.Connection is null))
                        {
                            Player.Connection.Dispose();
                        }
                    }

                    this.remotePlayersByEndpoint.Clear();
                    this.remotePlayers = null;
                }
            }
        }
        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            if (this.p2pNetwork != null)
            {
                this.p2pNetwork.Dispose();
                this.p2pNetwork = null;
            }

            if (this.peersByJid != null)
            {
                foreach (PeerState State in this.peersByJid.Values)
                {
                    State.ClearCallbacks();
                    State.Close();
                }

                this.peersByJid.Clear();
                this.peersByJid = null;
            }
        }
        public MultiPlayerEnvironment(string ApplicationName, bool AllowMultipleApplicationsOnSameMachine,
                                      string MqttServer, int MqttPort, bool MqttTls, string MqttUserName, string MqttPassword,
                                      string MqttNegotiationTopic, int EstimatedMaxNrPlayers, Guid PlayerId, params KeyValuePair <string, string>[] PlayerMetaInfo)
        {
            this.localPlayer           = new Player(PlayerId, new IPEndPoint(IPAddress.Any, 0), new IPEndPoint(IPAddress.Any, 0), PlayerMetaInfo);
            this.playersById[PlayerId] = this.localPlayer;
            this.applicationName       = ApplicationName;

            this.mqttServer           = MqttServer;
            this.mqttPort             = MqttPort;
            this.mqttTls              = MqttTls;
            this.mqttUserName         = MqttUserName;
            this.mqttPassword         = MqttPassword;
            this.mqttNegotiationTopic = MqttNegotiationTopic;

            this.p2pNetwork = new PeerToPeerNetwork(AllowMultipleApplicationsOnSameMachine ? this.applicationName + " (" + PlayerId.ToString() + ")" :
                                                    this.applicationName, 0, EstimatedMaxNrPlayers);
            this.p2pNetwork.OnStateChange         += this.P2PNetworkStateChange;
            this.p2pNetwork.OnPeerConnected       += new PeerConnectedEventHandler(p2pNetwork_OnPeerConnected);
            this.p2pNetwork.OnUdpDatagramReceived += new UdpDatagramEvent(p2pNetwork_OnUdpDatagramReceived);
        }
示例#9
0
        public static void Main(string[] args)
        {
            Initialize();

            try
            {
                using (PeerToPeerNetwork P2PNetwork = new PeerToPeerNetwork("Retro Peer-to-Peer example"))
                {
                    P2PNetwork.OnStateChange   += (sender, newstate) => Console.Out.WriteLine(newstate.ToString());
                    P2PNetwork.OnPeerConnected += (sender, connection) =>
                    {
                        Console.Out.WriteLine("Client connected from: " + connection.Tcp.Client.RemoteEndPoint.ToString());
                    };

                    if (!P2PNetwork.Wait())
                    {
                        throw new Exception("Unable to configure Internet Gateway NAT traversal.");
                    }

                    Console.Out.WriteLine("External IP Endpoint: " + P2PNetwork.ExternalEndpoint.ToString());

                    Console.Out.WriteLine("Press ENTER to try to connect.");
                    Console.In.ReadLine();

                    using (PeerConnection Client = P2PNetwork.ConnectToPeer(P2PNetwork.ExternalEndpoint))
                    {
                        Client.Start();
                        Console.In.ReadLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                Console.In.ReadLine();
            }

            Terminate();
        }
示例#10
0
        public async Task RunNetwork()
        {
            // arrange
            var runtime = new RuntimeController(new BasicValidator());


            var netSim  = new PeerToPeerNetworkSimulator(runtime);
            var netArgs = new NetworkArgs();

            netSim.OnExecuting += (o, e) =>
            {
                _network.AssociationMatrix.Each(ApplyAssociations);
            };
            netSim.With(netArgs);
            _network = netArgs.Network;
            _network.AddRange(ImportDevices().First());

            var simRepo = new SimulatorRepository();

            simRepo.Add(netSim);


            var pass      = 0;
            var maxPasses = 3;

            runtime.IterationPassed += (o, e) =>
            {
                pass++;
                if (pass == maxPasses)
                {
                    var dev = netArgs.Network.Items[0];
                    dev.Controls.Off();
                    _log.Trace($"Device '{dev.Name}' was turned off.");
                }
            };
            runtime.BindSimulators(simRepo)
            .Validate();

            // act iterations until availability is below 100%
            await runtime.RunAsync((r) =>
            {
                if (netArgs.Network.Availability() < 1)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            });

            // assert
            Assert.IsTrue(pass >= maxPasses, $"The iterations should be more than {maxPasses}.");
            netArgs.Network.DistanceMatrix.Each((r, c, v) =>
            {
                Assert.IsTrue(v > 0, $"position at row '{r}' and col '{c}' should not be '{v}'");
                _log.Trace($"{r}:{c} -> distance: {v}");
                return(v);
            });

            netArgs.Network.AngleMatrix.Each((r, c, v) =>
            {
                Assert.IsTrue(!float.IsNaN(v.Azimuth), $"Azimuth at position at row '{r}' and col '{c}' should not be NaN");
                Assert.IsTrue(!float.IsNaN(v.Elevation), $"Elevation at position at row '{r}' and col '{c}' should not be NaN");
                _log.Trace($"{r}:{c} -> angle: {v}");
                return(v);
            });
        }