Exemple #1
0
        public Peer(NetPeer peer)
        {
            this.peer = peer;

            //start the client
            peer.Start();
        }
Exemple #2
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			WriteToConsole("Type 'connect <host> <port>' to connect to another peer, or 'connect <port>' to connect to another localhost peer");

			NetConfiguration config = new NetConfiguration("p2pchat");
			config.MaxConnections = 256;
			s_peer = new NetPeer(config);
			//s_peer.VerboseLog = true;

			s_peer.SetMessageTypeEnabled(NetMessageType.ConnectionRejected | NetMessageType.BadMessageReceived | NetMessageType.VerboseDebugMessage, true);

			// start listening for incoming connections
			s_peer.Start();

			// create a buffer to read data into
			s_readBuffer = s_peer.CreateBuffer();

			Application.Idle += new EventHandler(OnAppIdle);
			Application.Run(s_mainForm);

			s_peer.Shutdown("Application exiting");
		}
Exemple #3
0
        public Program()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = API.MasterServer.MasterServerPort;

            peer = new NetPeer(config);
            peer.Start();
        }
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("unittests");
            config.EnableUPnP = true;
            NetPeer peer = new NetPeer(config);
            peer.Start(); // needed for initialization

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            NetQueueTests.Run();

            MiscTests.Run(peer);

            BitVectorTests.Run();

            EncryptionTests.Run(peer);

            var om = peer.CreateMessage();
            peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            try
            {
                peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            }
            catch (NetException nex)
            {
                if (nex.Message != "This message has already been sent! Use NetPeer.SendMessage() to send to multiple recipients efficiently")
                    throw nex;
            }

            peer.Shutdown("bye");

            // read all message
            NetIncomingMessage inc = peer.WaitMessage(5000);
            while (inc != null)
            {
                switch (inc.MessageType)
                {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        Console.WriteLine("Peer message: " + inc.ReadString());
                        break;
                    case NetIncomingMessageType.Error:
                        throw new Exception("Received error message!");
                }

                inc = peer.ReadMessage();
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemple #5
0
        public static void Connect(string ip, int port, params object[] data)
        {
            Peer = new NetClient(DefaultConfiguration);
            Peer.Start();
            var hailMessage = Peer.CreateMessage();

            foreach (var o in data)
            {
                hailMessage.Write(o);
            }
            Peer.Connect(ip, port, hailMessage);
        }
 public bool Init(Action <ITransportChannel> incommingConnectionAction)
 {
     if (_isInitialised)
     {
         throw new Exception("LidgrenNetProvider is already initialised");
     }
     _peer.Start();
     _listenEndpoint             = new IPEndPoint(_peer.Configuration.LocalAddress, _peer.Port);
     _processIncommingConnection = incommingConnectionAction;
     _isInitialised = true;
     return(true);
 }
Exemple #7
0
        public void Start()
        {
            peer = new NetPeer(config);
            peer.Start();
            localIdentifier = peer.UniqueIdentifier;

            listener = new peerListener(peer, localIdentifier);
            moveQueue = new Queue<string>();

            NetThread = new Thread(new ThreadStart(listener.processNetwork));
            NetThread.Start();
        }
Exemple #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MMC");
            config.MaximumConnections = 100;
            config.Port = 3939;
            // Enable DiscoveryResponse messages
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);

            s_server = new NetPeer(config);
            Output("listening on " + config.Port.ToString());
            s_server.Start();
        }
Exemple #9
0
 public static void Host(NetPeerConfiguration config)
 {
     Peer = new NetServer(config);
     Peer.Start();
     try
     {
         if (Peer.UPnP != null)
         {
             Peer.UPnP.ForwardPort(config.Port, $"{((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false))?.Title ?? string.Empty} {((AssemblyVersionAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyVersionAttribute), false))?.Version ?? "0"}");
         }
     }
     catch { }
 }
Exemple #10
0
        /// <summary>
        /// Start local network peer.  
        /// </summary>
        public Network()
        {
            m_netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            m_netPeerConfiguration.Port = APIMain.MasterServerPort;

            m_netPeer = new NetPeer(m_netPeerConfiguration);
            m_netPeer.Start();

            m_updateThread = new Thread(Update);
            m_updateThread.Start();

            m_updateServersListThread = new Thread(UpdateServerList);
            m_updateServersListThread.Start();
        }
Exemple #11
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm = new Form1();

            NetPeerConfiguration config = new NetPeerConfiguration("unconntest");
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.AcceptIncomingConnections = false; // don't accept connections; we're just using unconnected messages in this sample

            Peer = new NetPeer(config);
            Peer.Start();

            Application.Idle += new EventHandler(AppLoop);
            Application.Run(MainForm);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("unittests");
            NetPeer peer = new NetPeer(config);
            peer.Start(); // needed for initialization

            System.Threading.Thread.Sleep(50);

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            NetQueueTests.Run();

            MiscTests.Run(peer);

            BitVectorTests.Run();

            EncryptionTests.Run(peer);

            peer.Shutdown("bye");

            // read all message
            NetIncomingMessage inc;
            while((inc = peer.ReadMessage()) != null)
            {
                switch(inc.MessageType)
                {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        Console.WriteLine("Peer message: " + inc.ReadString());
                        break;
                    case NetIncomingMessageType.Error:
                        throw new Exception("Received error message!");
                }
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
        public PentagoNetwork(string playerName)
        {
            lastPingTime = DateTime.Now;
            nextPingTime = lastPingTime.AddSeconds(1);

            availablePeers = new List<peerType>();

            config = new NetPeerConfiguration("Pentago");
            // Enable DiscoveryResponse messages
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.EnableMessageType(NetIncomingMessageType.Data);
            config.ConnectionTimeout = 5;
            config.AcceptIncomingConnections = true;
            config.MaximumConnections = 32;
            config.Port = PORT_NUMBER;

            peer = new NetPeer(config);
            try
            {
                peer.Start();
                peerOn = true;

                Console.WriteLine("Peer Started");

                Thread t = new Thread(waitForMessages);
                t.SetApartmentState(ApartmentState.STA);
                peerName = playerName;
                t.Start();

                Console.WriteLine(peerName);

                peer.DiscoverLocalPeers(PORT_NUMBER);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Caught exception: " + ex.Data);
            }
        }
        public void startClient()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("SFML_Farseer_Network");

            _peer = new NetClient(config);
            _peer.Start();
            _role = NetRole.Client;
            _game.addMessage("Started client.");
        }
        static void Main(string[] args)
        {
            List<IPEndPoint[]> registeredHosts = new List<IPEndPoint[]>();

            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = CommonConstants.MasterServerPort;

            NetPeer peer = new NetPeer(config);
            peer.Start();

            // keep going until ESCAPE is pressed
            Console.WriteLine("Press ESC to quit");
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                NetIncomingMessage msg;
                while((msg = peer.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.UnconnectedData:
                            //
                            // We've received a message from a client or a host
                            //

                            // by design, the first byte always indicates action
                            switch ((MasterServerMessageType)msg.ReadByte())
                            {
                                case MasterServerMessageType.RegisterHost:
                                    // It's a host wanting to register its presence
                                    IPEndPoint[] eps = new IPEndPoint[]
                                    {
                                        msg.ReadIPEndpoint(), // internal
                                        msg.SenderEndpoint // external
                                    };
                                    Console.WriteLine("Got registration for host " + eps[1]);
                                    registeredHosts.Add(eps);
                                    break;

                                case MasterServerMessageType.RequestHostList:
                                    // It's a client wanting a list of registered hosts
                                    Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndpoint);
                                    foreach (IPEndPoint[] ep in registeredHosts)
                                    {
                                        // send registered host to client
                                        NetOutgoingMessage om = peer.CreateMessage();
                                        om.Write(ep[0]);
                                        om.Write(ep[1]);
                                        peer.SendUnconnectedMessage(om, msg.SenderEndpoint);
                                    }

                                    break;
                                case MasterServerMessageType.RequestIntroduction:
                                    // It's a client wanting to connect to a specific (external) host
                                    IPEndPoint clientInternal = msg.ReadIPEndpoint();
                                    IPEndPoint hostExternal = msg.ReadIPEndpoint();
                                    string token = msg.ReadString();

                                    Console.WriteLine(msg.SenderEndpoint + " requesting introduction to " + hostExternal + " (token " + token + ")");

                                    // find in list
                                    foreach (IPEndPoint[] elist in registeredHosts)
                                    {
                                        if (elist[1].Equals(hostExternal))
                                        {
                                            // found in list - introduce client and host to eachother
                                            Console.WriteLine("Sending introduction...");
                                            peer.Introduce(
                                                elist[0], // host internal
                                                elist[1], // host external
                                                clientInternal, // client internal
                                                msg.SenderEndpoint, // client external
                                                token // request token
                                            );
                                            break;
                                        }
                                    }
                                    break;
                            }
                            break;

                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            // print diagnostics message
                            Console.WriteLine(msg.ReadString());
                            break;
                    }
                }
            }

            peer.Shutdown("shutting down");
        }
Exemple #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server Started");
            
            Dictionary<IPEndPoint, AvailableGame> registeredHosts = new Dictionary<IPEndPoint, AvailableGame>();

            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = 6000;

            NetPeer peer = new NetPeer(config);
            peer.Start();

            // keep going until ESCAPE is pressed
            Console.WriteLine("Press ESC to quit");
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                System.Threading.Thread.Sleep(10);
                NetIncomingMessage msg;
                while ((msg = peer.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.UnconnectedData:
                            //
                            // We've received a message from a client or a host
                            //

                            // by design, the first byte always indicates action
                            switch (msg.ReadByte())
                            {
                                case 0: // register a new game
                                    // currently only one game per host per router.
                                    if (!registeredHosts.ContainsKey(msg.SenderEndpoint))
                                    {
                                        AvailableGame game = new AvailableGame();
                                        game.Count = msg.ReadInt32();
                                        game.GamerTag = msg.ReadString();
                                        game.PrivateGamerSlots = msg.ReadInt32();
                                        game.MaxGamers = msg.ReadInt32();
                                        game.IsHost = msg.ReadBoolean();
                                        game.InternalIP = msg.ReadIPEndpoint();
                                        game.ExternalIP = msg.SenderEndpoint;
                                        game.Game = msg.ReadString();


                                        Console.WriteLine("Got registration for host " + game.ToString());
                                        registeredHosts.Add(game.ExternalIP, game);
                                    }
                                    break;

                                case 1:
                                    // It's a client wanting a list of registered hosts
                                    Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndpoint);
                                    string appid = msg.ReadString();
                                    foreach (AvailableGame g1 in registeredHosts.Values)
                                    {
                                        if (g1.Game == appid)
                                        {
                                            // send registered host to client
                                            NetOutgoingMessage om = peer.CreateMessage();
                                            om.Write(g1.Count);
                                            om.Write(g1.GamerTag);
                                            om.Write(g1.PrivateGamerSlots);
                                            om.Write(g1.MaxGamers);
                                            om.Write(g1.IsHost);
                                            om.Write(g1.InternalIP);
                                            om.Write(g1.ExternalIP);
                                            peer.SendUnconnectedMessage(om, msg.SenderEndpoint);
                                        }
                                    }

                                    break;
                                case 2:
                                    // It's a client wanting to connect to a specific (external) host
                                    IPEndPoint clientInternal = msg.ReadIPEndpoint();
                                    IPEndPoint hostExternal = msg.ReadIPEndpoint();
                                    string token = msg.ReadString();

                                    Console.WriteLine(msg.SenderEndpoint + " requesting introduction to " + hostExternal + " (token " + token + ")");

                                    // find in list
                                    foreach (AvailableGame elist in registeredHosts.Values)
                                    {
                                        if (elist.ExternalIP.Equals(hostExternal))
                                        {
                                            // found in list - introduce client and host to eachother
                                            Console.WriteLine("Sending introduction...");
                                            peer.Introduce(
                                                    elist.InternalIP, // host internal
                                                    elist.ExternalIP, // host external
                                                    clientInternal, // client internal
                                                    msg.SenderEndpoint, // client external
                                                    token // request token
                                            );
                                            break;
                                        }
                                    }
                                    break;
                                case 3:
                                    if (registeredHosts.ContainsKey(msg.SenderEndpoint))
                                    {
                                        AvailableGame game = registeredHosts[msg.SenderEndpoint];
                                        string tag = msg.ReadString();
                                        string gamename = msg.ReadString();
                                        if (game.GamerTag == tag)
                                        {
                                            Console.WriteLine("Remove for host " + game.ExternalIP.ToString());
                                            registeredHosts.Remove(game.ExternalIP);
                                        }
                                    }
                                    break;
                                case 4 :
                                    if (registeredHosts.ContainsKey(msg.SenderEndpoint))
                                    {
                                        AvailableGame game = registeredHosts[msg.SenderEndpoint];
                                        int count = msg.ReadInt32();
                                        string tag = msg.ReadString();                                        
                                        if (game.GamerTag == tag)
                                        {
                                            Console.WriteLine("Update for host " + game.ExternalIP.ToString());                                            
                                            game.Count = count;
	                                        game.PrivateGamerSlots = msg.ReadInt32();
	                                        game.MaxGamers = msg.ReadInt32();
	                                        game.IsHost = msg.ReadBoolean();
	                                        game.InternalIP = msg.ReadIPEndpoint();
	                                        game.Game = msg.ReadString();
                                        }
                                    }
                                    break;
                            }
                            break;

                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            // print diagnostics message
                            Console.WriteLine(msg.ReadString());
                            break;
                    }
                }
            }

            peer.Shutdown("shutting down");

        }
Exemple #17
0
        static void Main(string[] args)
        {
            Dictionary<long, ServerData> registeredHosts = new Dictionary<long, ServerData>();

            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = SharedConfiguration.MasterServerEndPoint.Port;

            NetPeer peer = new NetPeer(config);
            peer.Start();

            // keep going until ESCAPE is pressed
            Console.WriteLine("Press ESC to quit");
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape) {
                NetIncomingMessage msg;
                while ((msg = peer.ReadMessage()) != null) {
                    switch (msg.MessageType) {
                        case NetIncomingMessageType.UnconnectedData:
                            //
                            // We've received a message from a client or a host
                            //

                            // by design, the first byte always indicates action
                            switch ((MasterServerMessageType)msg.ReadByte()) {
                                case MasterServerMessageType.RegisterHost:

                                    // It's a host wanting to register its presence
                                    var id = msg.ReadInt64(); // server unique identifier
                                    Console.WriteLine("Got registration for host " + id);

                                    ServerData serverData = new ServerData();
                                    serverData.IPEndPoint[0] = msg.ReadIPEndPoint();
                                    serverData.IPEndPoint[1] = msg.SenderEndPoint;

                                    serverData.ServerName = msg.ReadString();
                                    serverData.ScriptName = msg.ReadString();
                                    serverData.Players = msg.ReadInt32();
                                    serverData.MaxPlayers = msg.ReadInt32();

                                    registeredHosts[id] = serverData;
                                    break;

                                case MasterServerMessageType.RequestHostList:
                                    // It's a client wanting a list of registered hosts
                                    Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndPoint);
                                    foreach (var kvp in registeredHosts) {
                                        // send registered host to client
                                        NetOutgoingMessage om = peer.CreateMessage();
                                        om.Write(kvp.Key);
                                        om.Write(kvp.Value.IPEndPoint[0]);
                                        om.Write(kvp.Value.IPEndPoint[1]);
                                        om.Write(kvp.Value.ServerName);
                                        om.Write(kvp.Value.ScriptName);
                                        om.Write(kvp.Value.Players);
                                        om.Write(kvp.Value.MaxPlayers);
                                        peer.SendUnconnectedMessage(om, msg.SenderEndPoint);
                                    }

                                    break;
                            }
                            break;

                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            // print diagnostics message
                            Console.WriteLine(msg.ReadString());
                            break;
                    }
                }
            }

            peer.Shutdown("shutting down");
        }
Exemple #18
0
        public static void SendMCL()
        {
            Console.WriteLine("Enter Port: ");
            int port = int.Parse(Console.ReadLine());

            NetPeerConfiguration config = new NetPeerConfiguration("InduZtry");
            config.Port = port;
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.Data);
            config.AcceptIncomingConnections = true;
            //config.EnableUPnP = true;
            peer = new NetPeer(config);
            peer.Start();
            //Console.WriteLine("UPnP IP: " + peer.UPnP.GetExternalIP());

            Thread t = new Thread(RecvMCL);
            t.IsBackground = true;
            t.Start();

            //Console.WriteLine("Enter Server IP: ");
            //string sip = Console.ReadLine();
            Console.WriteLine("Enter Server Port: ");
            port = int.Parse(Console.ReadLine());
            //peer.DiscoverKnownPeer(sip, port);
            peer.DiscoverLocalPeers(port);
            //while(true) {
            //Thread.Sleep(10);
            //Console.WriteLine("Port: ");
            //int rport = int.Parse(Console.ReadLine());
            //peer.DiscoverLocalPeers(rport);
            //}
        }
Exemple #19
0
        public static void SendMCS()
        {
            Console.WriteLine("Enter Port: ");
            int port = int.Parse(Console.ReadLine());

            NetPeerConfiguration config = new NetPeerConfiguration("InduZtry");
            config.Port = port;
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.EnableMessageType(NetIncomingMessageType.Data);
            //config.EnableUPnP = true;
            server = new NetPeer(config);
            server.Start();
            //Console.WriteLine(server.UPnP.Status);
            //server.UPnP.ForwardPort(port, "InduZtry");
            //Console.WriteLine(server.UPnP.Status);
            //Console.WriteLine("UPnP IP: " + server.UPnP.GetExternalIP());

            Thread t = new Thread(RecvMCS);
            t.IsBackground = true;
            t.Start();

            message = "NULL";

            while(true) {
                Thread.Sleep(10);
                if(recipient != null) {
                    NetOutgoingMessage sendMsg = server.CreateMessage();
                    sendMsg.Write(message);
                    server.SendMessage(sendMsg, recipient, NetDeliveryMethod.ReliableOrdered);
                }
            }
        }
        private static void DoInit()
        {
            if (IsHost)
            {
                NetPeerConfiguration config = new NetPeerConfiguration("MonoPlatformerGame");
                config.Port = DataStorage.GetLocalPlayerConfig().ServerPort;
                config.MaximumConnections = 32;
                config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
                config.EnableUPnP = true;
                netPeer = new NetServer(config);
                netPeer.Start();
                netPeer.UPnP.ForwardPort(DataStorage.GetLocalPlayerConfig().ServerPort, "Server port");
                JapeLog.WriteLine("Server Started");
                Initialized = true;
            }
            else
            {
                NetPeerConfiguration config = new NetPeerConfiguration("MonoPlatformerGame");
                config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
                netPeer = new NetClient(config);

                NetOutgoingMessage hailMessage = CreateMessage();
                hailMessage.Write((int)DataType.Login);
                hailMessage.Write("Hello there");
                netPeer.Start();
                netPeer.Connect(DataStorage.GetLocalPlayerConfig().ServerIP, DataStorage.GetLocalPlayerConfig().ServerPort, hailMessage);
                Initialized = true;
            }
            //JapeLog.WriteLine("Connected to Server");
        }
 public bool Init(INetChannelConsumer factory)
 {
     _peer.Start();
     _peerFactory = factory;
     return(true);
 }
        public void startServer()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("SFML_Farseer_Network");

            config.Port = 3456;
            _peer = new NetServer(config);
            _peer.Start();
            _role = NetRole.Server;
            _game.addMessage("Started server on port 3456.");
        }
        /// <summary>
        /// Initialize system on port.
        /// </summary>
        /// <param name="port">The port.</param>
        public void StartPeer(int port)
        {
            // Check if already running
            EndPeers();
            CloseDevices();

            _netConfig = _netConfig.Clone();
            _netConfig.Port = port;

            // peerID
            var random = new Random();
            _peerID = random.Next(0, 100);

            switch (_config.SysType)
            {
                case SysType.Peer:
                    _netPeer = new NetPeer(_netConfig);
                    _netPeer.Start();

                    _peerIDString = "FUSEE3D:Peer:" + _peerID;

                    break;

                case SysType.Client:
                    _netClient = new NetClient(_netConfig);
                    _netClient.Start();

                    _peerIDString = "FUSEE3D:Client:" + _peerID;

                    break;

                case SysType.Server:
                    _netServer = new NetServer(_netConfig);
                    _netServer.Start();

                    _peerIDString = "FUSEE3D:Server:" + _peerID;

                    break;
            }
        }
Exemple #24
0
		internal static void Find (NetworkSessionType sessionType)
		{
			NetPeerConfiguration config = new NetPeerConfiguration (applicationIdentifier);			
			if (sessionType == NetworkSessionType.PlayerMatch) {
				config.EnableMessageType (NetIncomingMessageType.UnconnectedData);
				config.EnableMessageType (NetIncomingMessageType.NatIntroductionSuccess);
			} else {
				config.EnableMessageType (NetIncomingMessageType.DiscoveryRequest);
			}
            if (MonoGameNetworkConfiguration.Broadcast != IPAddress.None)
            {
                config.BroadcastAddress = MonoGameNetworkConfiguration.Broadcast;
            }
			netPeer = new NetPeer (config);
			netPeer.Start ();

			if (sessionType == NetworkSessionType.PlayerMatch) {
				GetServerList (netPeer);
			} else {
				netPeer.DiscoverLocalPeers (port);
			}

			DateTime now = DateTime.Now;

			discoveryMsgs = new List<NetIncomingMessage> ();

			do {
				NetIncomingMessage msg;
				while ((msg = netPeer.ReadMessage ()) != null) {
					switch (msg.MessageType) {
					case NetIncomingMessageType.DiscoveryResponse:
						discoveryMsgs.Add (msg);
						break;
					case NetIncomingMessageType.UnconnectedData:
						if (msg.SenderEndpoint.Equals (m_masterServer)) {
							discoveryMsgs.Add (msg);
							/*
				* // it's from the master server - must be a host
				IPEndPoint hostInternal = msg.ReadIPEndpoint();
				IPEndPoint hostExternal = msg.ReadIPEndpoint();

				m_hostList.Add(new IPEndPoint[] { hostInternal, hostExternal });                            
				*/
						}
						break;
					case NetIncomingMessageType.VerboseDebugMessage:
					case NetIncomingMessageType.DebugMessage:
					case NetIncomingMessageType.WarningMessage:
					case NetIncomingMessageType.ErrorMessage:
						//
						// Just print diagnostic messages to console
						//
#if DEBUG
						Console.WriteLine ("Find: " + msg.ReadString ());
#endif
						break;
					}
				}
			} while ((DateTime.Now - now).Seconds <= 2);

			netPeer.Shutdown ("Find shutting down");
		}
Exemple #25
0
        /// <summary>
        /// Подключение к P2P сервису. Для создания UDP окна.
        /// </summary>
        /// <param name="remotePoint">Адрес сервиса.</param>
        internal void ConnectToService(IPEndPoint remotePoint)
        {
            ThrowIfDisposed();

              if (Interlocked.CompareExchange(ref state, (int)PeerState.ConnectedToService, (int)PeerState.NotConnected) != (int)PeerState.NotConnected)
            throw new InvalidOperationException("Peer has not right state.");

              if (handler != null && handler.Status == NetPeerStatus.Running)
            throw new ArgumentException("Already runned.");

              var config = new NetPeerConfiguration(NetConfigString);
              config.Port = 0;
              config.AcceptIncomingConnections = true;
              config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

              if (remotePoint.AddressFamily == AddressFamily.InterNetworkV6)
            config.LocalAddress = IPAddress.IPv6Any;

              handler = new NetPeer(config);
              syncContext.Send(p => ((NetPeer)p).RegisterReceivedCallback(ReceivedCallback), handler);
              handler.Start();

              var hailMessage = handler.CreateMessage();
              using (var client = ClientModel.Get())
              {
            var localPoint = new IPEndPoint(Connection.GetIPAddress(remotePoint.AddressFamily), handler.Port);

            hailMessage.Write(client.User.Nick);
            hailMessage.Write(localPoint);
              }

              serviceConnection = handler.Connect(remotePoint, hailMessage);

              ClientModel.Logger.WriteDebug("AsyncPeer.ConnectToService({0})", remotePoint);
        }