Exemple #1
0
        public void PeerListener(NetPeer peer)
        {
            
            while (true)
            {
                NetIncomingMessage msg;
                while ((msg=peer.ReadMessage())!=null)
                {
                    NetConnection connection = msg.SenderConnection;

                    switch (msg.MessageType)
                    {
                      
                        case NetIncomingMessageType.StatusChanged:
                            switch (msg.SenderConnection.Status)
                            {    
                                case NetConnectionStatus.Connected:
                                    logger.Info("{0}: connected",connection.RemoteEndPoint.Address.ToString());
                                    ExecuteCommand(new CmdInitOk(connection));
                                    break;
                                case NetConnectionStatus.Disconnected:
                                    logger.Info("{0}: disconnected", connection.RemoteEndPoint.Address.ToString());
                                    break;
                                case NetConnectionStatus.Disconnecting:
                                    logger.Info("{0}: disconnecting", connection.RemoteEndPoint.Address.ToString());
                                    break;
                                    
                                                                                                     
                            }
                            break;
                    
                        case NetIncomingMessageType.Data:
                            msg.Decrypt(new NetRC2Encryption(peer, connection.CryptoKey));  
                            string[] OpData = msg.ReadString().Split('&');
                            var OpCode = (LoginOperation)Enum.Parse(typeof(LoginOperation), OpData[0]);

                            switch (OpCode)
                            {                                
                                case LoginOperation.AuthLog:   
                                    string[] authData = OpData[1].Split('#');
                                    string login = authData[0];
                                    string pass = authData[1];
                                    ExecuteCommand(new CmdLoginOkFail(connection, login,pass));
                                    break;
                            }


                            break;                    
                    }

                    peer.Recycle(msg);
                }
            }

        }
        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 #3
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();
        }
Exemple #4
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");
		}
        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 #6
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 #7
0
        void receiveData(GameTime gameTime)
        {
            timeSinceMessageReceived += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (timeSinceMessageReceived >= timeOutDelay)
            {
                waitingForMessage = true;
            }

            NetIncomingMessage msg;

            while ((msg = netPeer.ReadMessage()) != null)
            {
                timeSinceMessageReceived = 0f;
                waitingForMessage        = false;

                CurrentPing         = MathHelper.Max(connection.AverageRoundtripTime, OtherClientPing);
                currentScheduleTime = GameClock + CurrentPing * 1.5f;
                //currentScheduleTime = GameClock + .2f;
                timeOutDelay = MathHelper.Max(.53f, CurrentPing * 1.2f);

                if (msg.MessageType == NetIncomingMessageType.Data)
                {
                    byte id = msg.ReadByte();

                    if (id == MessageID.SYNC)
                    {
                        processSync(msg);
                    }
                    else if (id == MessageID.UNIT_MOVE_COMMAND_BATCH)
                    {
                        processUnitMoveCommandBatch(msg);
                    }
                    else if (id == MessageID.STRUCTURE_COMMAND)
                    {
                        processStructureCommand(msg);
                    }
                    else if (id == MessageID.RALLY_POINT_COMMAND)
                    {
                        processRallyPointCommand(msg);
                    }
                    else if (id == MessageID.UNIT_STATUS_UPDATE)
                    {
                        processUnitStatusUpdate(msg);
                    }
                    else if (id == MessageID.UNIT_HP_UPDATE)
                    {
                        processUnitHpUpdate(msg);
                    }
                    else if (id == MessageID.STRUCTURE_STATUS_UPDATE)
                    {
                        processStructureStatusUpdate(msg);
                    }
                    else if (id == MessageID.RESOURCE_STATUS_UPDATE)
                    {
                        processResourceStatusUpdate(msg);
                    }
                    else if (id == MessageID.UNIT_ATTACK_COMMAND_BATCH)
                    {
                        processUnitAttackCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_ATTACK_MOVE_COMMAND_BATCH)
                    {
                        processUnitAttackMoveCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_BUILD_COMMAND)
                    {
                        processUnitBuildCommand(msg);
                    }
                    else if (id == MessageID.UNIT_HARVEST_COMMAND_BATCH)
                    {
                        processUnitHarvestCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_RETURN_CARGO_COMMAND_BATCH)
                    {
                        processUnitReturnCargoCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_STOP_COMMAND_BATCH)
                    {
                        processUnitStopCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_HOLD_POSITION_COMMAND_BATCH)
                    {
                        processUnitHoldPositionCommandBatch(msg);
                    }
                    else if (id == MessageID.UNIT_DEATH)
                    {
                        processUnitDeath(msg);
                    }
                    else if (id == MessageID.STRUCTURE_DEATH)
                    {
                        processStructureDeath(msg);
                    }
                    else if (id == MessageID.UNIT_CANCEL_CONFIRMATION)
                    {
                        processUnitCancelConfirmation(msg);
                    }

                    /*else if (id == MessageID.PATH_UPDATE)
                     * {
                     *  processPathUpdate(msg);
                     * }*/
                }

                netPeer.Recycle(msg);
            }
        }
Exemple #8
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");
        }
        private static void Listen(NetPeer peer)
        {
            //TODO FIXME!

            if (peer == null)
                return;

            NetIncomingMessage msg;

            while ((msg = peer.ReadMessage()) != null)
            {
                switch (msg.MessageType)
                {
                    case NetIncomingMessageType.Data:
                        //JapeLog.WriteLine("Message received: Data");
                        IncomingData(msg);
                        break;
                    case NetIncomingMessageType.ConnectionApproval:

                        // Read the first byte of the packet
                        // ( Enums can be casted to bytes, so it be used to make bytes human readable )

                        int type = msg.ReadInt32();
                        if (type == (int)DataType.Login)
                        {
                            JapeLog.WriteLine("Incoming LOGIN");

                            msg.SenderConnection.Approve();
                            string hailMessage = msg.ReadString();

                            JapeLog.WriteLine("Approved new connection: " + hailMessage);
                        }
                        break;
                    case NetIncomingMessageType.StatusChanged:
                        if (msg.SenderConnection.Status == NetConnectionStatus.Connected)
                        {
                            if (!IsHost)
                            {
                                SendMessageParams(NetDeliveryMethod.ReliableOrdered,
                                    (int)DataType.NewPlayer,
                                    DataStorage.GetLocalPlayerConfig().UserName,
                                    (IsHost) ? 0 : -1,
                                    RemoteUID
                                    );

                                JapeLog.WriteLine("SEND NEWPLAYER");
                            }
                            else
                                JapeLog.WriteLine("This server is Dedicated (Not sending a new player message)");
                        }
                        if (msg.SenderConnection.Status == NetConnectionStatus.Disconnected)
                        {
                            JapeLog.WriteLine("Player Disconnected");
                            //if player is in connected => remove from play
                        }
                        if (msg.SenderConnection.Status == NetConnectionStatus.Disconnecting)
                        {
                            JapeLog.WriteLine("Player Disconnecting");
                            //if player is in connected => remove from play
                        }
                        break;
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        //JapeLog.WriteLine(msg.ReadString());
                        break;
                }
                peer.Recycle(msg);
            }
        }