Exemple #1
0
        public static void Process(NetServer server, NetBuffer buffer, NetConnection sender)
        {
            Config config = Config.Instance;

            List<NetConnection> connections = server.Connections;

            //Lets send that message onto any plugin clients
            foreach (NetConnection connection in connections)
            {
                if (config.Server.client_connections.ContainsKey(connection.RemoteEndpoint.ToString()))
                {
                    string client_type = (string)config.Server.client_connections[connection.RemoteEndpoint.ToString()];

                    if (client_type.ToLower() == "plugin")
                    {
                        string msg = buffer.ReadString();

                        Console.WriteLine("Slave: Data sent - " + msg);

                        NetBuffer slavebuf = server.CreateBuffer();

                        slavebuf.Write(msg);

                        server.SendMessage(slavebuf, connection, NetChannel.ReliableInOrder4);
                    }
                }
            }
        }
Exemple #2
0
        private static void HandleMessage(NetIncomingMessage inc, NetServer server)
        {
            switch (inc.MessageType)
            {
                case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request
                    if (inc.ReadByte() == (byte) PacketTypes.Headers.Login)
                    {
                        string username = inc.ReadString();
                        Console.WriteLine("New Login Request from: {0}", username);
                        if (username.Length > 1 & Players.Values.All(c => c.Name != username) &
                            !_badwordList.Contains(username, StringComparer.OrdinalIgnoreCase))
                        {
                            inc.SenderConnection.Approve();
                            NetOutgoingMessage connectedMessage = server.CreateMessage();
                            Thread.Sleep(500);
                            Console.WriteLine("Sending a ack to {0}", username);
                            connectedMessage.Write((byte) PacketTypes.Headers.LoggedIn);
                            connectedMessage.Write(true);
                            server.SendMessage(connectedMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                        }
                        else
                        {
                            inc.SenderConnection.Deny("Bad Username");
                        }
                    }

                    break;

                case NetIncomingMessageType.Data:
                    byte packetheader = inc.ReadByte();
                    HandleProtocol(inc, packetheader, server);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);
                    if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected)
                    {
                        Console.WriteLine("Player: {0} has disconnected",
                            Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
                        Players.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
                    }
                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    NetOutgoingMessage discovermsg = server.CreateMessage();
                    discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
                    Console.WriteLine(@"Auto Discovery Request");
                    server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
                    break;

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine(@"---Debug---");
                    Console.WriteLine(inc.ReadString());
                    Console.WriteLine(@"---End---");
                    break;
            }
        }
Exemple #3
0
 private static void SendMessage(NetServer server, MsgBase msg, NetConnection conn)
 {
     NetOutgoingMessage om = server.CreateMessage();
     om.Write(msg.Id);
     msg.W(om);
     server.SendMessage(om, conn, NetDeliveryMethod.Unreliable, 0);
 }
        public void Send(NetConnection conn, NetBuffer data)
        {
            if (netconn == null)
            {
                return;
            }
            var msg = netconn.CreateMessage();

            msg.Write(data);
            netconn.SendMessage(msg, conn, NetDeliveryMethod.ReliableOrdered);
        }
Exemple #5
0
 private static void DispatchPacket(NetServer server, int id, NetIncomingMessage msg)
 {
     List<NetConnection> all = server.Connections;
     all.Remove(msg.SenderConnection);
     if (all.Count > 0)
     {
         NetOutgoingMessage om = server.CreateMessage();
         om.Write(id);
         om.Write(msg);
         server.SendMessage(om, all, NetDeliveryMethod.Unreliable, 0);
     }
 }
Exemple #6
0
        public static void SendMessageExceptOne(NetServer server, IMessage msg, NetConnection except)
        {
            NetOutgoingMessage om = server.CreateMessage();
            om.Write(msg.Id);
            msg.Write(om);

            List<NetConnection> all = server.Connections;
            if (all.Contains(except))
            {
                all.Remove(except);
            }
            if (all.Count > 0)
            {
                server.SendMessage(om, all, NetDeliveryMethod.Unreliable, 0);
            }
        }
Exemple #7
0
        private void LoginMessageImpl(NetServer server, NetIncomingMessage im, MessageBase msg)
        {
            var registerMsg = msg as LoginMessage;
            var r = new LoginResultMessage();

            var user = AdventurePluginDB.User.Get(registerMsg.Name, registerMsg.Pass);
            if (user != null)
            {
                r.Result = "OK";
                r.UserId = user.id;
            }
            else
            {
                r.Result = "Error";
            }
            server.SendMessage(r, im.SenderConnection);
        }
Exemple #8
0
        private void RegisterMessageImpl(NetServer server, NetIncomingMessage im, MessageBase msg)
        {
            var registerMsg = msg as RegisterMessage;
            var r = new RegisterResultMessage();

            if (AdventurePluginDB.User.Get(registerMsg.Name, registerMsg.Pass) == null)
            {
                var user = new UserInfo
                {
                    Name = registerMsg.Name,
                    Pass = registerMsg.Pass,
                };
                AdventurePluginDB.User.Create(user);
                r.Result = "OK";
            }
            else
            {
                r.Result = "Error";
            }
            server.SendMessage(r, im.SenderConnection);
        }
Exemple #9
0
 private static void ConnectionApproval(NetIncomingMessage inc, NetServer server)
 {
     Console.WriteLine("======== CONNECTION APPROVAL METHOD ========");
        Console.WriteLine("\nNew Connection Incoming...");
        var data = inc.ReadByte();
        if (data == (byte)PacketType.Login)
        {
             var outMsg = server.CreateMessage();
             outMsg.Write((byte)PacketType.Login);
             outMsg.Write(true);
             Console.WriteLine(inc.SenderConnection);
             Console.WriteLine("Server sending reply...");
             server.SendMessage(outMsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
             //Console.WriteLine(inc.SenderConnection.Status);
             //Console.WriteLine("Connected: " + server.ConnectionsCount);
             Console.WriteLine("======== CONNECTION APPROVAL METHOD ======== \n");
        }
        else
        {
             inc.SenderConnection.Deny("Didn't send correct information.");
        }
 }
Exemple #10
0
        static void Main(string[] args)
        {
            // Create new instance of configs. Parameter is "application Id". It has to be same on client and server.
            Config = new NetPeerConfiguration("game");

            // Set server port
            Config.Port = 14242;

            // Max client amount
            Config.MaximumConnections = 200;

            // Enable New messagetype. Explained later
            Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            // Create new server based on the configs just defined
            Server = new NetServer(Config);

            // Start it
            Server.Start();

            // Eh..
            Console.WriteLine("Server Started");

            // Create list of "Characters" ( defined later in code ). This list holds the world state. Character positions
            List<Character> GameWorldState = new List<Character>();

            // Object that can be used to store and read messages
            NetIncomingMessage inc;

            // Check time
            DateTime time = DateTime.Now;

            // Create timespan of 30ms
            TimeSpan timetopass = new TimeSpan(0, 0, 0, 0, 30);

            // Write to con..
            Console.WriteLine("Waiting for new connections and updateing world state to current ones");

            // Main loop
            // This kind of loop can't be made in XNA. In there, its basically same, but without while
            // Or maybe it could be while(new messages)
            while (true)
            {
                // Server.ReadMessage() Returns new messages, that have not yet been read.
                // If "inc" is null -> ReadMessage returned null -> Its null, so dont do this :)
                if ((inc = Server.ReadMessage()) != null)
                {
                    // Theres few different types of messages. To simplify this process, i left only 2 of em here
                    switch (inc.MessageType)
                    {
                        // If incoming message is Request for connection approval
                        // This is the very first packet/message that is sent from client
                        // Here you can do new player initialisation stuff
                        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 )
                            if (inc.ReadByte() == (byte)PacketTypes.LOGIN)
                            {
                                Console.WriteLine("Incoming LOGIN");

                                // Approve clients connection ( Its sort of agreenment. "You can be my client and i will host you" )
                                inc.SenderConnection.Approve();

                                // Init random
                                Random r = new Random();

                                // Add new character to the game.
                                // It adds new player to the list and stores name, ( that was sent from the client )
                                // Random x, y and stores client IP+Port
                                GameWorldState.Add(new Character(inc.ReadString(), r.Next(1, 40), r.Next(1, 20),inc.SenderConnection));

                                // Create message, that can be written and sent
                                NetOutgoingMessage outmsg = Server.CreateMessage();

                                // first we write byte
                                outmsg.Write((byte)PacketTypes.WORLDSTATE);

                                // then int
                                outmsg.Write(GameWorldState.Count);

                                // iterate trought every character ingame
                                foreach (Character ch in GameWorldState)
                                {
                                    // This is handy method
                                    // It writes all the properties of object to the packet
                                    outmsg.WriteAllProperties(ch);
                                }

                                // Now, packet contains:
                                // Byte = packet type
                                // Int = how many players there is in game
                                // character object * how many players is in game

                                // Send message/packet to all connections, in reliably order, channel 0
                                // Reliably means, that each packet arrives in same order they were sent. Its slower than unreliable, but easyest to understand
                                Server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);

                                // Debug
                                Console.WriteLine("Approved new connection and updated the world status");
                            }

                            break;
                        // Data type is all messages manually sent from client
                        // ( Approval is automated process )
                        case NetIncomingMessageType.Data:

                            // Read first byte
                            if (inc.ReadByte() == (byte)PacketTypes.MOVE)
                            {
                                // Check who sent the message
                                // This way we know, what character belongs to message sender
                                foreach (Character ch in GameWorldState)
                                {
                                    // If stored connection ( check approved message. We stored ip+port there, to character obj )
                                    // Find the correct character
                                    if (ch.Connection != inc.SenderConnection)
                                        continue;

                                    // Read next byte
                                    byte b = inc.ReadByte();

                                    // Handle movement. This byte should correspond to some direction
                                    if ((byte)MoveDirection.UP == b)
                                        ch.Y--;
                                    if ((byte)MoveDirection.DOWN == b)
                                        ch.Y++;
                                    if ((byte)MoveDirection.LEFT == b)
                                        ch.X--;
                                    if ((byte)MoveDirection.RIGHT == b)
                                        ch.X++;

                                    // Create new message
                                    NetOutgoingMessage outmsg = Server.CreateMessage();

                                    // Write byte, that is type of world state
                                    outmsg.Write((byte)PacketTypes.WORLDSTATE);

                                    // Write int, "how many players in game?"
                                    outmsg.Write(GameWorldState.Count);

                                    // Iterate throught all the players in game
                                    foreach (Character ch2 in GameWorldState)
                                    {
                                        // Write all the properties of object to message
                                        outmsg.WriteAllProperties(ch2);
                                    }

                                    // Message contains
                                    // Byte = PacketType
                                    // Int = Player count
                                    // Character obj * Player count

                                    // Send messsage to clients ( All connections, in reliable order, channel 0)
                                    Server.SendMessage(outmsg, Server.Connections, NetDeliveryMethod.ReliableOrdered, 0);
                                    break;
                                }

                            }
                            break;
                        case NetIncomingMessageType.StatusChanged:
                            // In case status changed
                            // It can be one of these
                            // NetConnectionStatus.Connected;
                            // NetConnectionStatus.Connecting;
                            // NetConnectionStatus.Disconnected;
                            // NetConnectionStatus.Disconnecting;
                            // NetConnectionStatus.None;

                            // NOTE: Disconnecting and Disconnected are not instant unless client is shutdown with disconnect()
                            Console.WriteLine(inc.SenderConnection.ToString() + " status changed. " + (NetConnectionStatus)inc.SenderConnection.Status);
                            if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected || inc.SenderConnection.Status == NetConnectionStatus.Disconnecting)
                            {
                                // Find disconnected character and remove it
                                foreach (Character cha in GameWorldState)
                                {
                                    if (cha.Connection == inc.SenderConnection)
                                    {
                                        GameWorldState.Remove(cha);
                                        break;
                                    }
                                }
                            }
                            break;
                        default:
                            // As i statet previously, theres few other kind of messages also, but i dont cover those in this example
                            // Uncommenting next line, informs you, when ever some other kind of message is received
                            //Console.WriteLine("Not Important Message");
                            break;
                    }
                } // If New messages

                // if 30ms has passed
                if ((time + timetopass) < DateTime.Now)
                {
                    // If there is even 1 client
                    if (Server.ConnectionsCount != 0)
                    {
                        // Create new message
                        NetOutgoingMessage outmsg = Server.CreateMessage();

                        // Write byte
                        outmsg.Write((byte)PacketTypes.WORLDSTATE);

                        // Write Int
                        outmsg.Write(GameWorldState.Count);

                        // Iterate throught all the players in game
                        foreach (Character ch2 in GameWorldState)
                        {

                            // Write all properties of character, to the message
                            outmsg.WriteAllProperties(ch2);
                        }

                        // Message contains
                        // byte = Type
                        // Int = Player count
                        // Character obj * Player count

                        // Send messsage to clients ( All connections, in reliable order, channel 0)
                        Server.SendMessage(outmsg, Server.Connections, NetDeliveryMethod.ReliableOrdered, 0);
                    }
                    // Update current time
                    time = DateTime.Now;
                }

                // While loops run as fast as your computer lets. While(true) can lock your computer up. Even 1ms sleep, lets other programs have piece of your CPU time
                //System.Threading.Thread.Sleep(1);
            }
        }
Exemple #11
0
        private static void Main(string[] args)
        {
            //TODO: Chat
            //TODO: UPnP
            //TODO: Fix Simulated Conditions

            config = new NetPeerConfiguration("spacebargame") {Port = 666, EnableUPnP = true, MaximumConnections = 50};

            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            server = new NetServer(config);
            server.Start();
            server.UPnP.ForwardPort(666, "Spacebar Game 2013");

            NetIncomingMessage inc; // Incoming Message

            //Write to con..
            var consoleInput = new Thread(ConsoleIn); //Console.ReadLine is blocked, Thread it
            consoleInput.Start(); //Start the Thread

            UserToConnection = new Dictionary<long, Client>(); //UserStore

            while (true) //While True
            {
                if ((inc = server.ReadMessage()) != null) //if message is not null
                {
                    //Console.WriteLine(inc.MessageType); //Print MessageType
                    switch (inc.MessageType)
                    {
                        case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request

                            if (inc.ReadByte() == (byte) PacketTypes.LOGIN) //and LOGIN PacketHeader
                            {
                                Console.WriteLine("Incoming LOGIN"); //Incoming Login

                                Name = inc.ReadString(); //Name is String Sent by Client
                                Console.WriteLine(Name); //Print Name

                                if (server.ConnectionsCount == 0) //ConnectionCount = 0
                                {
                                    Started = false; //Reset
                                }

                                if (UserToConnection.Values.Any(c => c.Name == Name) || Started || Name.Length >= 12)
                                    //If Name exists, or Game has Started or the Length is more then 12
                                {
                                    inc.SenderConnection.Deny("Duplicate Name"); //Deny
                                }
                                else
                                {
                                    inc.SenderConnection.Approve(); //Else Allow
                                    UserToConnection.Add(inc.SenderConnection.RemoteUniqueIdentifier,
                                        new Client(Name, inc.SenderConnection, 0, new byte[00000000]));
                                    //Add them to the Dictionary for PlayerStore
                                }

                                Thread.Sleep(500); //Sleep for Half a Second

                                if (server.ConnectionsCount == 1) //If Server.ConnectionCount is 1 they are host
                                {
                                    NetOutgoingMessage msg = server.CreateMessage(); //Host Message
                                    msg.Write((byte) PacketTypes.HOST); //Write HOST PacketHeader
                                    msg.Write("Congratulations, You are the host");
                                    server.SendMessage(msg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                                }
                            }
                            break;

                        case NetIncomingMessageType.Data:

                            var packetheader = inc.ReadByte();

                            switch ((PacketTypes) packetheader)
                            {
                                case PacketTypes.AVATAR:
                                    var bufferLength = inc.ReadInt32();
                                    var buffer = inc.ReadBytes(bufferLength);
                                    Console.WriteLine("Buffer Length:" + bufferLength);

                                    UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer = buffer;
                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();

                                            syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
                                            syncClient.Write(Name);
                                            syncClient.Write(inc.SenderConnection.RemoteUniqueIdentifier);

                                            var buffer1 =
                                                UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer;

                                            syncClient.Write(buffer1.Length);
                                            syncClient.Write(buffer1);

                                            Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", Name,
                                                inc.SenderConnection.RemoteUniqueIdentifier);
                                            Console.WriteLine("TO: {0}, {1}", entry.Value.Name, entry.Value.Score);
                                            server.SendMessage(syncClient, entry.Value.Connection,
                                                NetDeliveryMethod.ReliableOrdered); //OTHERPEOPLE
                                        }
                                    }

                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        //if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();

                                            syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
                                            syncClient.Write(entry.Value.Name);
                                            syncClient.Write(entry.Key);

                                            var buffer1 = entry.Value.Buffer;

                                            syncClient.Write(buffer1.Length);
                                            syncClient.Write(buffer1);
                                            Console.WriteLine(buffer1.Length);

                                            Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", entry.Value.Name,
                                                entry.Key);
                                            Console.WriteLine("TO: {0}", inc.SenderConnection);

                                            server.SendMessage(syncClient, inc.SenderConnection,
                                                NetDeliveryMethod.ReliableOrdered); //CLIENT
                                        }
                                    }

                                    break;

                                case PacketTypes.SENDPOS:
                                    UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score =
                                        Convert.ToInt16(inc.ReadString());
                                    Console.WriteLine("{0}'s score is now: {1}",
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);
                                    ID = inc.SenderConnection.RemoteUniqueIdentifier;
                                    UpdateScore();

                                    break;

                                case PacketTypes.STARTGAME:
                                    //GOGOGOGO
                                    Console.WriteLine("START THE GAME");
                                    Started = true;

                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();
                                            syncClient.Write((byte) PacketTypes.STARTGAME);
                                            syncClient.Write("Go");
                                            syncClient.Write(
                                                UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);

                                            server.SendMessage(syncClient, entry.Value.Connection,
                                                NetDeliveryMethod.ReliableOrdered);
                                        }
                                    }

                                    break;

                                case PacketTypes.CHATSEND:
                                    string messager = inc.ReadString();

                                    Console.WriteLine("{0} : {1}",
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
                                        messager);

                                    RelayChat(inc.SenderConnection.RemoteUniqueIdentifier, messager);

                                    break;
                            }

                            break;

                        case NetIncomingMessageType.StatusChanged:

                            Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);

                            if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected ||
                                inc.SenderConnection.Status == NetConnectionStatus.Disconnecting)
                            {
                                UserToConnection.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
                                NetOutgoingMessage outmsg = server.CreateMessage();
                                outmsg.WriteVariableInt64(inc.SenderConnection.RemoteUniqueIdentifier);
                                server.SendToAll(outmsg, NetDeliveryMethod.ReliableOrdered);
                            }
                            break;

                        case NetIncomingMessageType.DiscoveryRequest:
                            NetOutgoingMessage discovermsg = server.CreateMessage();
                            discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
                            Console.WriteLine("WOW ~NETWORKING~");
                            server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
                            break;
                    }
                }
                Thread.Sleep(1);
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            //Setup the policy server first.

            const string AllPolicy =
            @"<?xml version='1.0'?>
            <cross-domain-policy>
            <allow-access-from domain=""*"" to-ports=""*"" />
            </cross-domain-policy>";

            SocketPolicyServer policyServer = new SocketPolicyServer(AllPolicy);
            int ret = policyServer.Start();
            if (ret != 0)
                Console.WriteLine("Failed to start policy server.");
            else
                Console.WriteLine("Policy service started.");

            //Alright, now onto the regular server.
            config = new NetPeerConfiguration("crab_battle");
            config.Port = 14248;
            config.MaximumConnections = 10;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            server = new NetServer(config);
            server.Start();

            Console.WriteLine("Crab Battle server open for business.");

            NetIncomingMessage inc;

            DateTime time = DateTime.Now;
            DateTime lastBeat = DateTime.Now;
            DateTime introtime = DateTime.Now;

            TimeSpan timetopass = new TimeSpan(0,0,0,0,50);
            TimeSpan beatrate = new TimeSpan(0, 0, 1);

            TimeSpan introlength;

            bool skipintro = false;

            if(skipintro == true)
                introlength = new TimeSpan(0, 0, 3);
            else
                introlength = new TimeSpan(0, 0, 21);

            int beatnum = 0;

            players = new List<PlayerObject>();

            int playercount = 0;

            NetOutgoingMessage outmsg;

            int gamePhase = 0;

            int gameDifficulty = 1;
            healthMod = 1;

            CrabBehavior crab = new CrabBehavior();

            while(true)
            {
                //The gamestate stuff comes first because we drop a continue if no packet is recieved.

                if (gamePhase != (int)GameState.Lobby && players.Count == 0)
                {
                    Console.WriteLine("All players disconnected, returning to lobby gamestate.");
                    gamePhase = (int)GameState.Lobby;
                }

                if (gamePhase == (int)GameState.Intro && ((introtime + introlength) < DateTime.Now))
                {
                    //Intro has ran for it's length, lets start the game proper.
                    outmsg = server.CreateMessage();
                    outmsg.Write((byte)PacketTypes.StartGame);
                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                    crab.Direction = false;

                    gamePhase = (int)GameState.InGame;
                }

                if(gamePhase == (int)GameState.InGame)
                {
                    crab.GoGoBattleCrab();
                }

                //Handle dropping players.

                if ((time + timetopass) < DateTime.Now)
                {
                    for (int i = 0; i < players.Count; i++)
                    {
                        PlayerObject player = players[i];

                        //Make sure everyone is connected, and if not drop them.
                        if (player.Connection.Status == NetConnectionStatus.Disconnected || player.Connection.Status == NetConnectionStatus.Disconnecting)
                        {
                            Console.WriteLine(player.Name + " has disconnected, removing player object.");
                            SendLobbyMessage("Server", player.Name + " has disconnected.");

                            outmsg = server.CreateMessage();
                            outmsg.Write((byte)PacketTypes.RemovePlayer);
                            outmsg.Write((Int16)player.Id);
                            server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                            players.Remove(player);

                            outmsg = server.CreateMessage();
                            outmsg.Write((byte)PacketTypes.PlayerCount);
                            outmsg.Write((Int16)players.Count);
                            server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                        }
                        else
                        {
                            if (player.LastBeat + 5 < beatnum)
                            {
                                player.Connection.Disconnect("Timeout");
                                Console.WriteLine(player.Name + " has not responded in over 10 seconds.  Closing connection.");
                            }
                        }
                    }

                    time = DateTime.Now;
                }

                //Send update beats.

                if ((lastBeat + beatrate) < DateTime.Now)
                {
                    //Send a beat to all users.  Because the server doesn't really know if they disconnected unless we are sending packets to them.
                    //Beats go out every 2 seconds.
                    foreach (PlayerObject p in players)
                    {
                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.Beat);
                        outmsg.Write((Int16)beatnum);
                        outmsg.Write(p.Connection.AverageRoundtripTime/2f);
                        server.SendMessage(outmsg, p.Connection, NetDeliveryMethod.ReliableOrdered, 1);
                    }
                    beatnum++;

                    lastBeat = DateTime.Now;
                }

                // IT'S PACKET TIME

                if ((inc = server.ReadMessage()) == null) continue;

                switch(inc.MessageType)
                {
                    case NetIncomingMessageType.ConnectionApproval:
                        //A new connection! If the game is not currently ongoing, we'll accept this connection.

                        Console.WriteLine("Incoming login request. " + inc.SenderConnection.ToString());

                        if (gamePhase > 0)
                        {
                            inc.SenderConnection.Deny("The server is already running a game.");
                            break;
                        }

                        Console.WriteLine("Assigning new player the name of Player " + (playercount+1) + ".");

                        inc.SenderConnection.Approve();

                        players.Add(new PlayerObject(playercount+1, inc.SenderConnection, "Player "+(playercount+1), beatnum));

                        SendLobbyMessage("Server", "Player " + (playercount + 1) + " has connected.  Connected players: " + players.Count);

                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.Message);
                        outmsg.Write("You are now connected to CrabBattle Server.");
                        server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 1);

                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.AssignId);
                        outmsg.Write((Int32)(playercount + 1));
                        server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 1);

                        //Send the current playercount to the client.
                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.PlayerCount);
                        outmsg.Write((Int16)players.Count);
                        server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 1);

                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.PlayerCount);
                        outmsg.Write((Int16)players.Count);
                        server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                        //Send difficulty settings to the new player

                        Console.WriteLine(gameDifficulty + " " + healthMod);

                        outmsg = server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.SettingsChange);
                        outmsg.Write((Int16)gameDifficulty);
                        outmsg.Write((Int16)healthMod);
                        server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 1);

                        playercount++;

                        break;

                    case NetIncomingMessageType.Data:

                        PlayerObject player = players.Find(p => p.Connection == inc.SenderConnection);
                        if (player == null)
                            break; //Don't accept data from connections that don't have a player attached.

                        switch ((PacketTypes)inc.ReadByte())
                        {
                            case PacketTypes.LobbyMessage:
                                {
                                    string msg = inc.ReadString();
                                    SendLobbyMessage(player.Name, msg);
                                    Console.WriteLine(player.Name + ": " + msg);
                                }
                                break;
                            case PacketTypes.SettingsChange:
                                {
                                    //Difficulty or health mod changed, broadcast changes to all clients.
                                    gameDifficulty = inc.ReadInt16();
                                    healthMod = inc.ReadInt16();

                                    Console.WriteLine(player.Name + " changed difficulty/healthmod to " + gameDifficulty + "/" + healthMod + ".");

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.SettingsChange);
                                    outmsg.Write((Int16)gameDifficulty);
                                    outmsg.Write((Int16)healthMod);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                                }
                                break;
                            case PacketTypes.Beat:
                                {
                                    player.LastBeat = inc.ReadInt16();
                                    player.X = inc.ReadFloat();
                                    player.Y = inc.ReadFloat();

                                    if (crab.CurrentTarget == player.Id)
                                    {
                                        float CrabX = inc.ReadFloat();
                                        float CrabZ = inc.ReadFloat();

                                        if (crab.random.Next(0, 10) > 8)
                                            crab.Direction = !crab.Direction;

                                        //Crab position and target sync.
                                        outmsg = server.CreateMessage();
                                        outmsg.Write((byte)PacketTypes.EnemySync);
                                        outmsg.Write((Int16)player.Id); //Id of the current crab controller.
                                        outmsg.Write(CrabX); //EnemyX
                                        outmsg.Write(CrabZ); //EnemyZ
                                        outmsg.Write(player.X);
                                        outmsg.Write(player.Y);
                                        outmsg.Write(crab.Direction);
                                        outmsg.Write(player.Connection.AverageRoundtripTime/2f); //Divide by 2 to get trip time.
                                        server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                                    }
                                }
                                break;
                            case PacketTypes.Ready:
                                {
                                    //Player is ready to start the game.
                                    player.Ready = inc.ReadBoolean();

                                    Console.WriteLine(player.Name + " changed their ready status to " + player.Ready);
                                    if (player.Ready)
                                        SendLobbyMessage("Server", player.Name + " is now Ready.");
                                    else
                                        SendLobbyMessage("Server", player.Name + " is no longer ready.");
                                }
                                break;
                            case PacketTypes.UpdateName:
                                {
                                    //Player changed their name.  Since the clients aren't aware of each other until the game starts,
                                    //there's no need to broadcast this message to other users.
                                    string newname = inc.ReadString();
                                    Console.WriteLine(player.Name + " changed their name to '" + newname + "'.");
                                    SendLobbyMessage("Server", player.Name + " changed their name to '" + newname + "'.");

                                    player.Name = newname;
                                }
                                break;
                            case PacketTypes.Disconnect:
                                {
                                    //Player requests to disconnect from the server.
                                    Console.WriteLine(player.Name + " has disconnected, removing player object.");

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.RemovePlayer);
                                    outmsg.Write((Int16)player.Id);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                                    players.Remove(player);

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.PlayerCount);
                                    outmsg.Write((Int16)players.Count);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                                }
                                break;
                            case PacketTypes.StartGame:
                                {
                                    //Someone clicked start game.  Lets make sure everyone is ready and we're in a state where we can start.
                                    if (gamePhase != (int)GameState.Lobby)
                                        break;

                                    bool ready = true;

                                    foreach (PlayerObject p in players)
                                        ready = ready & p.Ready;

                                    if (ready)
                                    {
                                        outmsg = server.CreateMessage();
                                        outmsg.Write((byte)PacketTypes.Message);
                                        outmsg.Write("All players ready, launching game.");
                                        server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                                        Console.WriteLine("All set, launching Game!");

                                        float numplayers = players.Count();
                                        float curplayer = ((numplayers-1) * 20f) / 2f * -1f;

                                        for (int i = 0; i < players.Count; i++)
                                        {
                                            PlayerObject p = players[i];

                                            //Lets create all the player objects for all players, 20 paces apart.
                                            outmsg = server.CreateMessage();
                                            outmsg.Write((byte)PacketTypes.AddPlayer);
                                            outmsg.Write((Int16)p.Id);

                                            p.X = curplayer;
                                            p.Y = -500f; //Hardcoded ftw!

                                            curplayer += 20f;

                                            outmsg.Write(p.X);
                                            outmsg.Write(p.Y);

                                            outmsg.Write(p.Name);

                                            server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                                        }

                                        outmsg = server.CreateMessage();
                                        outmsg.Write((byte)PacketTypes.PlayIntro);
                                        server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                                        gamePhase = (int)GameState.Intro;

                                        crab = new CrabBehavior(); //Prepare the CRAB!

                                        introtime = DateTime.Now;
                                    }
                                    else
                                    {
                                        outmsg = server.CreateMessage();
                                        outmsg.Write((byte)PacketTypes.Message);
                                        outmsg.Write("A player attempted to start the game, but not all players are ready.");
                                        server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
                                        SendLobbyMessage("Server", "Game cannot start until all users are ready.");
                                    }
                                }
                                break;
                            case PacketTypes.PlayerSpecial:
                                {
                                    int shottype = inc.ReadInt16();

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.PlayerSpecial);
                                    outmsg.Write((Int16)player.Id);
                                    outmsg.Write((Int16)shottype);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableUnordered, 0);
                                    //Console.WriteLine("Relaying Special Action Message for " + player.Name + ".");
                                }
                                break;
                            case PacketTypes.PlayerAction:
                                {
                                    //Player hit a key or something!  Change their status, broadcast to other users.

                                    //Set player values
                                    //inc.ReadInt16(); //Player id is submitted, but not used.
                                    player.X = inc.ReadFloat();
                                    player.Y = inc.ReadFloat();
                                    player.VelocityX = inc.ReadFloat();
                                    player.VelocityY = inc.ReadFloat();
                                    player.Firing = inc.ReadBoolean();

                                    //Broadcast them to everyone else
                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.PlayerAction);
                                    outmsg.Write((Int16)player.Id);
                                    outmsg.Write(player.X);
                                    outmsg.Write(player.Y);
                                    outmsg.Write(player.VelocityX);
                                    outmsg.Write(player.VelocityY);
                                    outmsg.Write(player.Firing);
                                    outmsg.Write(player.Connection.AverageRoundtripTime/2f); //Not an exact science, but we'll use this to predict their position.
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);

                                    //Console.WriteLine("Relaying Action Message for " + player.Name + ". "+player.VelocityX + " " + player.VelocityY);
                                }
                                break;
                            case PacketTypes.HurtTarget:
                                {
                                    int damage = inc.ReadInt16();

                                    crab.CurrentHealth -= damage;
                                    bool hittype = inc.ReadBoolean();

                                    if (!hittype)
                                        player.dmgnormal += damage;
                                    else
                                        player.dmgweakpoint += damage;

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.EnemyHealth);
                                    outmsg.Write((Int16)crab.CurrentHealth);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.Unreliable, 0);
                                }
                                break;
                            case PacketTypes.PlayerHit:
                                {
                                    player.hitstaken += 1;

                                    outmsg = server.CreateMessage();
                                    outmsg.Write((byte)PacketTypes.PlayerHit);
                                    outmsg.Write((Int16)player.Id);
                                    server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableUnordered, 0);
                                }
                                break;
                        }
                        break;
                    case NetIncomingMessageType.StatusChanged:
                        {
                            //Players connection status changed.
                            PlayerObject p1 = players.Find(p => p.Connection == inc.SenderConnection);
                            if (p1 == null)
                                break;

                            Console.WriteLine(p1.Name + " status changed to " + (NetConnectionStatus)inc.SenderConnection.Status + ".");
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    static void Main(string[] args)
    {
        int loopStartTime = 0;
        int loopEndTime = 0;
        float deltaSecond = 0;

        //Frequency to return data
        const float ReturnDataPerSecond = 20;
        float lastSentData = 0;

        //Team containers
        ShapeTeamContainer greenTeam = new ShapeTeamContainer(ShapeTeam.GREEN);
        ShapeTeamContainer redTeam = new ShapeTeamContainer(ShapeTeam.RED);

        NetPeerConfiguration config = new NetPeerConfiguration("ShapeSpace");
        config.Port = 55678;
        config.MaximumConnections = maxPlayers;
        config.ConnectionTimeout = 10;
        config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
        config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

        server = new NetServer(config);
        //Console.WriteLine(server.Configuration.LocalAddress);

        physicsWorld = new World(Vector2.Zero);
        //50px = 1m
        ConvertUnits.SetDisplayUnitToSimUnitRatio(50f);

        try
        {
            server.Start();
        }
        catch(Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(e);
            Console.ForegroundColor = ConsoleColor.White;
            WaitForKeyPress();
        }

        Console.WriteLine("Server Started Sucessfully!");

        //Main program loop
        while(true)
        {
            deltaSecond = (loopEndTime - loopStartTime) / 1000f;

            lastSentData += deltaSecond;

            loopStartTime = Environment.TickCount;

            //Handle incoming messages
            NetIncomingMessage msg;
            while ((msg = server.ReadMessage()) != null)
            {
                //Console.WriteLine(msg.MessageType);
                switch (msg.MessageType)
                {
                    case NetIncomingMessageType.Data:
                        //A swith handling ShapeSpace custom message types
                        switch((ShapeCustomNetMessageType)msg.ReadByte())
                        {
                            case ShapeCustomNetMessageType.InputUpdate:
                                int playerIndex = msg.ReadInt32();
                                float timeSinceLast = msg.ReadFloat();
                                Vector2 input = msg.ReadVector2();

                                connectedPlayers[playerIndex].inputs.Add(new InputWithTime(timeSinceLast,input));

                                //Console.WriteLine(timeSinceLast + ": " + input.ToString());
                                break;
                            case ShapeCustomNetMessageType.SetupRequest:
                                NetOutgoingMessage returnMessage = server.CreateMessage();

                                NetworkPlayer newPlayer = new NetworkPlayer(physicsWorld, msg.SenderConnection, new Vector2(0,0));

                                //ShapeTeam team = (ShapeTeam)msg.ReadByte();
                                string username = msg.ReadString();

                                try
                                {
                                    //newPlayer.SetTeam(team);
                                    newPlayer.SetUserName(username);

                                    int spot = AddNewPlayer(newPlayer);

                                    newPlayer.indexOnServer = spot;

                                    //Assign the new player to the team with the least amount of players
                                    ShapeTeamContainer newPlayerTeam = greenTeam.GetNumberOfMembers() < redTeam.GetNumberOfMembers() ? greenTeam : redTeam;
                                    bool isBank = newPlayerTeam.AddPlayer(newPlayer.indexOnServer);
                                    newPlayer.SetTeam(newPlayerTeam.GetTeam());
                                    newPlayer.body.Position = ConvertUnits.ToSimUnits(newPlayerTeam.basePosition);

                                    if (isBank)
                                        newPlayer.SetClass(new ShapeClassBank());
                                    else
                                        newPlayer.SetClass(new ShapeClassKnocker());

                                    newPlayer.OnCreateRemnant += CreateRemnant;
                                }
                                catch(Exception e)
                                {
                                    returnMessage.Write((byte)ShapeCustomNetMessageType.SetupFailed);
                                    returnMessage.Write(e.Message);
                                    server.SendMessage(returnMessage, newPlayer.netConnection, NetDeliveryMethod.ReliableUnordered);
                                    break;
                                }

                                returnMessage.Write((byte)ShapeCustomNetMessageType.SetupSuccessful);
                                returnMessage.Write(newPlayer.indexOnServer);
                                returnMessage.Write((byte)newPlayer.team);

                                returnMessage.Write(connectedPlayersActual);

                                for (int i = 0; i < connectedPlayers.Length; i++)
                                {
                                    if(connectedPlayers[i] != null)
                                    {
                                        returnMessage.Write(connectedPlayers[i].indexOnServer);
                                        returnMessage.Write((byte)connectedPlayers[i].team);
                                        returnMessage.Write(connectedPlayers[i].power);
                                    }
                                }

                                server.SendMessage(returnMessage, newPlayer.netConnection, NetDeliveryMethod.ReliableUnordered);

                                if(connectedPlayersActual > 1)
                                {
                                    NetOutgoingMessage newPlayerMessage = server.CreateMessage();
                                    newPlayerMessage.Write((byte)ShapeCustomNetMessageType.NewPlayerJoined);

                                    newPlayerMessage.Write(newPlayer.indexOnServer);
                                    newPlayerMessage.Write((byte)newPlayer.team);
                                    newPlayerMessage.Write(/*newPlayer.power*/5);

                                    server.SendMessage(newPlayerMessage, GetRecipients(newPlayer.indexOnServer), NetDeliveryMethod.ReliableUnordered, 0);
                                }

                                Console.WriteLine("Player connected");
                                break;
                        }
                        break;
                    case NetIncomingMessageType.DiscoveryRequest:
                        NetOutgoingMessage response = server.CreateMessage();
                        response.Write("This is a Shape Space server");
                        server.SendDiscoveryResponse(response, msg.SenderEndPoint);
                        break;
                    case NetIncomingMessageType.ConnectionApproval:
                        Console.WriteLine("A client is asking to connect");
                        //Approve the connection and send back a hailmessage containing server info back
                        NetOutgoingMessage hailMessage = server.CreateMessage();
                        hailMessage.Write(maxPlayers);

                        msg.SenderConnection.Approve(hailMessage);
                        break;
                    case NetIncomingMessageType.StatusChanged:
                        if(msg.ReadByte() == (byte)NetConnectionStatus.Disconnected)
                        {
                            //Console.WriteLine("Player disconnected: " + FindPlayerByNetConnection(msg.SenderConnection).Username);

                            RemovePlayer(msg.SenderConnection);
                        }
                        break;
                    default:
                        Console.WriteLine("Unhandled type: " + msg.MessageType + " Info: \"" + msg.ReadString() + "\"");
                        break;
                }
                server.Recycle(msg);
            }

            //Move players
            UpdatePlayers(deltaSecond);

            //Simulate the world
            physicsWorld.Step(1f/100f);

            //Return data to clients
            if (lastSentData >= 1f/ReturnDataPerSecond && connectedPlayersActual > 0)
            {
                //List<NetConnection> recipients = new List<NetConnection>();

                NetOutgoingMessage outMess = server.CreateMessage();
                outMess.Write((byte)ShapeCustomNetMessageType.LocationUpdate);
                outMess.Write(connectedPlayersActual);

                for (int i = 0; i < maxPlayers; i++)
                {
                    if (connectedPlayers[i] != null)
                    {
                        outMess.Write(connectedPlayers[i].indexOnServer);
                        outMess.Write(connectedPlayers[i].power);
                        outMess.Write(lastSentData);
                        outMess.Write(ConvertUnits.ToDisplayUnits(connectedPlayers[i].body.Position));

                        int trailCount = connectedPlayers[i].trail.Count;
                        outMess.Write(trailCount);

                        for(int j = 0; j < trailCount; j++)
                        {
                            //outMess.Write(connectedPlayers[i].trail[j].Id);
                            outMess.Write(connectedPlayers[i].trail[j].position);
                            outMess.Write(connectedPlayers[i].trail[j].size);
                        }
                    }
                }

                //Write all remnants positions
                int remnantCount = remnants.Count;
                outMess.Write(remnantCount);

                for (int j = 0; j < remnantCount; j++)
                {
                    outMess.Write(remnants[j].position);
                    outMess.Write(remnants[j].size);
                }

                server.SendMessage(outMess, GetRecipients(-1), NetDeliveryMethod.UnreliableSequenced, 2);

                lastSentData = 0;
            }

            //Make sure the server runs at about 60 frames per second
            if(deltaSecond * 1000 < 1000/17)
                Thread.Sleep(Convert.ToInt32(1000/17 - deltaSecond * 1000));

            loopEndTime = Environment.TickCount;
        }
    }
        static void Main(string[] args)
        {
            Config = new NetPeerConfiguration("pokemon");
            Config.Port = 7377;
            Config.MaximumConnections = 20;
            Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            Server = new NetServer(Config);

            Server.Start();

            Console.WriteLine("time to own");

            /*/Creating a ContentManager to load maps from XML
            Form form = new Form();
            GraphicsDeviceService gds = GraphicsDeviceService.AddRef(form.Handle,
                    form.ClientSize.Width, form.ClientSize.Height);

            ServiceContainer services = new ServiceContainer();
            services.AddService<IGraphicsDeviceService>(gds);
            content = new ContentManager(services, "Content");*/

            //Initialize all the maps here

            List<PlayerPrimitive> Players = new List<PlayerPrimitive>();

            ServerNPCController = new NPCController();
            NPC npc = new NPC(null, new Vector2(15, 15), 2);
            ServerNPCController.addNPC(npc);

            NetIncomingMessage nic;

            DateTime time = DateTime.Now;

            TimeSpan updateSpan = new TimeSpan(0, 0, 0, 0, 30);

            Console.WriteLine("Waiting for players to join...");

            while (true)
            {
                if ((nic = Server.ReadMessage()) != null)
                {
                    switch (nic.MessageType)
                    {
                        case NetIncomingMessageType.ConnectionApproval :
                            if (nic.ReadByte() == (byte)PacketTypes.Login)
                            {
                                Console.WriteLine("New Player joining.");

                                nic.SenderConnection.Approve();

                                PlayerPrimitive prim = DataReadWrite.ReadPlayer(nic);
                                prim.Connection = nic.SenderConnection;

                                Players.Add(prim);

                                Console.WriteLine("The following players are in:");
                                foreach (PlayerPrimitive player in Players)
                                {
                                    Console.WriteLine(player.Name + " joined " + System.DateTime.Now);
                                    Console.WriteLine(player.UniqueId);
                                }

                                NetOutgoingMessage outmsg = Server.CreateMessage();

                                outmsg.Write((byte)PacketTypes.WorldState);

                                outmsg.Write(Players.Count);

                                foreach (PlayerPrimitive player in Players)
                                {
                                    outmsg.WriteAllProperties(player);
                                }

                                Server.SendMessage(outmsg, nic.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);

                                Console.WriteLine("New player has joined, server updated and shit.");

                            }
                            break;

                        case NetIncomingMessageType.Data :

                            if (nic.ReadByte() == (byte)PacketTypes.Move)
                            {
                                foreach (PlayerPrimitive player in Players)
                                {
                                    if (player.Connection != nic.SenderConnection)
                                        continue;

                                    Vector2 position = XNAExtensions.ReadVector2(nic);
                                    bool running = nic.ReadBoolean();

                                    player.X = (int)position.X;
                                    player.Y = (int)position.Y;
                                    player.IsRunning = running;

                                    Console.WriteLine(player.Name + " position: " + player.X + ", " + player.Y + ": running = " + running);

                                    /*NetOutgoingMessage outmsg = Server.CreateMessage();

                                    outmsg.Write((byte)PacketTypes.WorldState);
                                    outmsg.Write(Players.Count);

                                    foreach (PlayerPrimitive playa in Players)
                                        outmsg.WriteAllProperties(playa);

                                    Server.SendMessage(outmsg, Server.Connections, NetDeliveryMethod.ReliableOrdered, 0);*/
                                    break;
                                }

                            }

                            break;

                        case NetIncomingMessageType.StatusChanged :

                            Console.WriteLine(nic.SenderConnection.ToString() + " status changed." + (NetConnectionStatus)nic.SenderConnection.Status);

                            if (nic.SenderConnection.Status == NetConnectionStatus.Disconnected ||
                                nic.SenderConnection.Status == NetConnectionStatus.Disconnecting)
                            {
                                foreach (PlayerPrimitive player in Players)
                                {
                                    if (player.Connection == nic.SenderConnection)
                                    {
                                        Players.Remove(player);
                                        Console.WriteLine(player.Name + " left the game " + System.DateTime.Now);
                                        break;
                                    }
                                }
                            }
                            break;

                        default :

                            Console.WriteLine("Message type is: " + nic.MessageType);

                            break;
                    }
                }

                if ((time + updateSpan) < DateTime.Now)
                {
                    ServerNPCController.UpdateNPCs(updateSpan);

                    if (Server.ConnectionsCount > 0)
                    {
                        NetOutgoingMessage outmsg = Server.CreateMessage();
                        outmsg.Write((byte)PacketTypes.WorldState);
                        outmsg.Write(Players.Count);
                        outmsg.Write(ServerNPCController.NPCs.Count);

                        foreach (PlayerPrimitive player in Players)
                            outmsg.WriteAllProperties(player);

                        foreach (NPC nerdo in ServerNPCController.NPCs)
                            outmsg.WriteAllProperties(nerdo.toPrimitive());

                        Server.SendMessage(outmsg, Server.Connections, NetDeliveryMethod.ReliableOrdered, 0);
                    }

                    time = DateTime.Now;
                }

                System.Threading.Thread.Sleep(1);
            }
        }
Exemple #15
0
        private static Player NewPlayer(NetIncomingMessage inc, NetServer server, string username)
        {
            var newPlayer = new Player(username);
            foreach (long key in Players.Keys)
            {
                NetOutgoingMessage msgToNewClient = server.CreateMessage();
                msgToNewClient.Write((byte) PacketTypes.Headers.PlayerRec);
                msgToNewClient.Write(key);
                msgToNewClient.Write(Players[key].Name);
                msgToNewClient.Write(Players[key].GetReadyStatus());

                Console.WriteLine("NClient: Sent message about {0} to: {1}", username, Players[key].Name);
                server.SendMessage(msgToNewClient, inc.SenderConnection,
                    NetDeliveryMethod.ReliableOrdered);

                NetOutgoingMessage msgToCurrentClient = server.CreateMessage();
                msgToCurrentClient.Write((byte) PacketTypes.Headers.PlayerRec);
                msgToCurrentClient.Write(inc.SenderConnection.RemoteUniqueIdentifier);
                msgToCurrentClient.Write(username);
                msgToCurrentClient.Write(false);

                Console.WriteLine("CClient: Sent message about {0} to: {1}", Players[key].Name, username);
                server.SendMessage(msgToCurrentClient, Players[key].Connection, NetDeliveryMethod.ReliableOrdered);
            }
            return newPlayer;
        }
Exemple #16
0
        static void Main(string[] args)
        {
            sem = new Semaphore(1, 1);
            NetPeerConfiguration config = new NetPeerConfiguration("robotcontra");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.Port = 16868;

            Thread _writeClientUpdate = new Thread(new ThreadStart(writeClientsUpdate));

            // create and start server
            server = new NetServer(config);
            server.Start();

            gameOver = false;
            finishWritingLevel = false;

            // schedule initial sending of position updates
            double nextSendUpdates = NetTime.Now;

            _writeClientUpdate.Start();

            // run until escape is pressed
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                NetIncomingMessage msg;
                while ((msg = server.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DiscoveryRequest:
                            //
                            // Server received a discovery request from a client; send a discovery response (with no extra data attached)
                            //

                            server.SendDiscoveryResponse(null, msg.SenderEndPoint);
                            break;
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            //
                            // Just print diagnostic messages to console
                            //
                            Console.WriteLine(msg.ReadString());
                            break;
                        case NetIncomingMessageType.StatusChanged:
                            NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                            if (status == NetConnectionStatus.Connected)
                            {
                                //
                                // A new player just connected!
                                //
                                Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");

                                multiplayerPlayers.Add(new MultiplayerPlayers(msg.SenderConnection.RemoteUniqueIdentifier));

                                // randomize his position and store in connection tag
                                if (multiplayerPlayers.Count <= 1)
                                {
                                    multiplayerPlayers[0].x = 10;
                                    multiplayerPlayers[0].y = 350;

                                    multiplayerPlayers[0].initialX = multiplayerPlayers[0].x;
                                    multiplayerPlayers[0].initialY = multiplayerPlayers[0].y;
                                }
                                else
                                {
                                    multiplayerPlayers[multiplayerPlayers.Count-1].x = multiplayerPlayers[multiplayerPlayers.Count - 2].x + 70;
                                    multiplayerPlayers[multiplayerPlayers.Count-1].y = multiplayerPlayers[multiplayerPlayers.Count - 2].y;

                                    multiplayerPlayers[multiplayerPlayers.Count - 1].initialX = multiplayerPlayers[multiplayerPlayers.Count - 1].x;
                                    multiplayerPlayers[multiplayerPlayers.Count - 1].initialY = multiplayerPlayers[multiplayerPlayers.Count - 1].y;
                                }

                                for (int i = 0; i < server.Connections.Count; i++)
                                {
                                    if (server.Connections[i].RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier)
                                    {
                                        NetConnection player = server.Connections[i] as NetConnection;
                                        NetOutgoingMessage outMessage = server.CreateMessage();
                                        outMessage.Write((byte)PacketTypes.CREATEPLAYER);
                                        outMessage.Write((long)multiplayerPlayers[i].id);
                                        outMessage.Write((float)multiplayerPlayers[i].x);
                                        outMessage.Write((float)multiplayerPlayers[i].y);
                                        server.SendMessage(outMessage, player, NetDeliveryMethod.ReliableOrdered);
                                        break;
                                    }
                                }

                                SetEnemyTarget();
                            }
                            else if (status == NetConnectionStatus.Disconnected || status == NetConnectionStatus.Disconnecting)
                            {
                                Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " DISCONNECTED FROM SERVER!");

                                for (int i = 0; i < multiplayerPlayers.Count; i++)
                                {
                                    if (multiplayerPlayers[i].id == msg.SenderConnection.RemoteUniqueIdentifier)
                                    {
                                        if (multiplayerPlayers[i].isHost)
                                        {
                                            if (multiplayerPlayers.Count > 1)
                                            {
                                                multiplayerPlayers[i + 1].isHost = true;

                                                NetConnection player = server.Connections[i];

                                                NetOutgoingMessage outMsg = server.CreateMessage();
                                                outMsg.Write((byte)PacketTypes.CHANGEHOST);
                                                outMsg.Write((bool)multiplayerPlayers[i + 1].isHost);

                                                server.SendMessage(outMsg, player, NetDeliveryMethod.ReliableOrdered);

                                            }
                                        }

                                        multiplayerPlayers.RemoveAt(i);
                                        if (deletePlayerFromServer(msg.SenderConnection.RemoteUniqueIdentifier))
                                        {
                                            Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " DELETED!");
                                        }
                                        else
                                        {
                                            Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " IS NOT EXIST!");
                                        }

                                        foreach (NetConnection player in server.Connections)
                                        {
                                            NetOutgoingMessage outMessage = server.CreateMessage();
                                            outMessage.Write((byte)PacketTypes.DELETEPLAYER);
                                            outMessage.Write((long)msg.SenderConnection.RemoteUniqueIdentifier);

                                            server.SendMessage(outMessage, player, NetDeliveryMethod.ReliableOrdered);
                                        }

                                        SetEnemyTarget();
                                        SendToAllPlayerEnemyTarget();

                                        break;
                                    }
                                }
                            }

                            break;
                        case NetIncomingMessageType.Data:

                            switch (msg.ReadByte())
                            {
                                case (byte)PacketTypes.MYPOSITION:
                                    CharacterState state = (CharacterState)msg.ReadByte();
                                    CharacterState laststate = (CharacterState)msg.ReadByte();
                                    int health = msg.ReadInt32();
                                    float xPosition = msg.ReadFloat();
                                    float yPosition = msg.ReadFloat();

                                    foreach (MultiplayerPlayers players in multiplayerPlayers)
                                    {
                                        if (players.id == msg.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            players.state = state;
                                            players.lastState = laststate;
                                            players.health = health;
                                            players.x = xPosition;
                                            players.y = yPosition;
                                            break;
                                        }
                                    }
                                    break;

                                case (byte)PacketTypes.UPDATEVELOCITY:
                                    CharacterState currState = (CharacterState)msg.ReadByte();
                                    CharacterState lastState = (CharacterState)msg.ReadByte();

                                    float lastPosX = msg.ReadFloat();
                                    float lastPosY = msg.ReadFloat();

                                    float updateVelX = msg.ReadFloat();
                                    float updateVelY = msg.ReadFloat();

                                    foreach (MultiplayerPlayers players in multiplayerPlayers)
                                    {
                                        if (players.id == msg.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            players.state = currState;
                                            players.lastState = lastState;
                                            players.lastPosX = lastPosX;
                                            players.lastPosY = lastPosY;
                                            players.velocityX = updateVelX;
                                            players.velocityY = updateVelY;
                                        }
                                    }

                                    for (int i = 0; i < server.Connections.Count; i++)
                                    {
                                        NetConnection player = server.Connections[i] as NetConnection;
                                        // ... send information about every other player (actually including self)
                                        for (int j = 0; j < server.Connections.Count; j++)
                                        {
                                            // send position update about 'otherPlayer' to 'player'
                                            NetOutgoingMessage om = server.CreateMessage();

                                            // write who this position is for

                                            om.Write((byte)PacketTypes.SENDUPDATEVELOCITY);
                                            om.Write((long)multiplayerPlayers[j].id);
                                            om.Write((byte)multiplayerPlayers[j].state);
                                            om.Write((byte)multiplayerPlayers[j].lastState);
                                            om.Write((float)multiplayerPlayers[j].lastPosX);
                                            om.Write((float)multiplayerPlayers[j].lastPosY);
                                            om.Write((float)multiplayerPlayers[j].velocityX);
                                            om.Write((float)multiplayerPlayers[j].velocityY);

                                            // send message
                                            server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                                        }

                                    }

                                    break;

                                    case (byte)PacketTypes.SENDPLAYERDEAD:
                                    foreach (MultiplayerPlayers players in multiplayerPlayers)
                                    {
                                        if (players.id == msg.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            players.isDead = true;
                                        }
                                    }
                                    SetEnemyTarget();
                                    SendToAllPlayerEnemyTarget();
                                    break;

                                case (byte)PacketTypes.GETNUMBEROFPLAYERS:
                                    NetOutgoingMessage msgOut = server.CreateMessage();

                                    msgOut.Write((byte)PacketTypes.GETNUMBEROFPLAYERS);
                                    msgOut.Write((short)multiplayerPlayers.Count);
                                    server.SendMessage(msgOut, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered);

                                    break;

                                case (byte)PacketTypes.WRITELEVEL:
                                    enemies.Clear();

                                    for (int i = 0; i < multiplayerPlayers.Count; i++)
                                    {
                                        if (multiplayerPlayers[i].id == msg.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            multiplayerPlayers[i].isHost = true;
                                        }
                                    }

                                    int enemiesInLevel = msg.ReadInt16();
                                    level = msg.ReadInt16();

                                    for (int i = 0; i < enemiesInLevel; i++)
                                    {
                                        Enemy tempEnemy = new Enemy();
                                        tempEnemy.isDead = false;

                                        tempEnemy.health = msg.ReadInt16();
                                        tempEnemy.state = (CharacterState)msg.ReadByte();
                                        tempEnemy.lastState = (CharacterState)msg.ReadByte();
                                        tempEnemy.x = msg.ReadFloat();
                                        tempEnemy.y = msg.ReadFloat();

                                        enemies.Add(tempEnemy);

                                    }
                                    SetEnemyTarget();
                                    SendToAllPlayerEnemyTarget();
                                    finishWritingLevel = true;
                                    break;

                                case (byte)PacketTypes.UPDATEENEMYPOSITION:

                                    for (int i = 0; i < enemies.Count; i++)
                                    {
                                        if (finishWritingLevel == true)
                                        {
                                            enemies[i].health = msg.ReadInt32();
                                            enemies[i].state = (CharacterState)msg.ReadByte();
                                            enemies[i].lastState = (CharacterState)msg.ReadByte();
                                            enemies[i].x = msg.ReadFloat();
                                            enemies[i].y = msg.ReadFloat();
                                        }
                                    }

                                    SendToAllEnemyPositionsToPlayers();
                                    break;

                                case (byte)PacketTypes.DELETEENEMY:
                                    int enemyDead = msg.ReadInt16();
                                    if (enemies.Count > 0 && finishWritingLevel == true)
                                        enemies[enemyDead].isDead = true;
                                    break;

                                case (byte)PacketTypes.GETSERVERENEMYPOSITIONS:
                                    msgOut = server.CreateMessage();

                                    msgOut.Write((byte)PacketTypes.SENDENEMYPOSITIONS);

                                    for (int i = 0; i < enemies.Count; i++)
                                    {

                                        msgOut.Write((byte)enemies[i].state);
                                        msgOut.Write((byte)enemies[i].lastState);
                                        msgOut.Write((bool)enemies[i].isDead);
                                        msgOut.Write((float)enemies[i].x);
                                        msgOut.Write((float)enemies[i].y);
                                    }

                                    server.SendMessage(msgOut, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered);

                                    break;

                                case (byte)PacketTypes.GETSERVERLEVEL:
                                    msgOut = server.CreateMessage();

                                    msgOut.Write((byte)PacketTypes.GETLEVEL);
                                    msgOut.Write((short)level);
                                    msgOut.Write((short)enemies.Count);

                                    for (int i = 0; i < enemies.Count; i++)
                                    {
                                        msgOut.Write((byte)enemies[i].state);
                                        msgOut.Write((byte)enemies[i].lastState);
                                        msgOut.Write((short)enemies[i].health);
                                        msgOut.Write((bool)enemies[i].isDead);
                                        msgOut.Write((float)enemies[i].x);
                                        msgOut.Write((float)enemies[i].y);

                                    }
                                    server.SendMessage(msgOut, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                                    break;

                                case (byte)PacketTypes.GETENEMYTARGETPLAYER:
                                    SetEnemyTarget();
                                    SendToAllPlayerEnemyTarget();

                                    break;

                                case (byte)PacketTypes.GAMEOVER:
                                    gameOver = true;
                                    break;
                            }
                            break;
                    }

                }

                double now = NetTime.Now;
                if (now > nextSendUpdates)
                {
                    // Yes, it's time to send position updates

                    // for each player...
                    for (int i = 0; i < server.Connections.Count; i++)
                    {
                        NetConnection player = server.Connections[i] as NetConnection;
                        // ... send information about every other player (actually including self)
                        for (int j = 0; j < multiplayerPlayers.Count; j++)
                        {
                            // send position update about 'otherPlayer' to 'player'
                            NetOutgoingMessage om = server.CreateMessage();

                            // write who this position is for
                            om.Write((byte)PacketTypes.UPDATEPLAYERS);
                            om.Write((long)multiplayerPlayers[j].id);
                            om.Write((byte)multiplayerPlayers[j].state);
                            om.Write((byte)multiplayerPlayers[j].lastState);
                            om.Write((int)multiplayerPlayers[j].health);
                            om.Write((bool)multiplayerPlayers[j].isDead);
                            om.Write((float)multiplayerPlayers[j].x);
                            om.Write((float)multiplayerPlayers[j].y);

                            // send message
                            server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                        }

                    }
                    // schedule next update
                    nextSendUpdates += (1.0 / 60.0);
                }
                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }

            server.Shutdown("app exiting");
        }
Exemple #17
0
 static void Main(string[] args)
 {
     Globals.Init();
     server = new NetServer(Globals.config);
     WriteLine("Building Map");
     WriteLine("Server Starting");
     server.Start();
     while (true)
     {
         while (server.MessageAvailable)
         {
             NetIncomingMessage msg = server.ReadMessage();
             switch (msg.MessageType)
             {
                 case NetIncomingMessageType.VerboseDebugMessage:
                 case NetIncomingMessageType.WarningMessage:
                 case NetIncomingMessageType.DebugMessage:
                 case NetIncomingMessageType.ErrorMessage:
                     WriteLine(msg.ReadString());
                     break;
                 case NetIncomingMessageType.Data:
                     string netStr = msg.ReadString();
                     switch (netStr.Substring(0, 4))
                     {
                         case "NICK":
                             string newNick = netStr.Substring(4);
                             string str1 = " : " + GetPlayerNick(msg.SenderConnection) + " : Changed there Nickname to " + newNick;
                             WriteLine(newNick + str1);
                             if (Connections.Count > 0)
                             {
                                 for (int i = 0; i < Connections.Count; i++)
                                 {
                                     if (Connections[i].Connection == msg.SenderConnection)
                                     {
                                         Player update = Connections[i];
                                         update.Name = newNick;
                                         Connections[i] = update;
                                     }
                                 }
                             }
                             SendToAll("[Server]", str1);
                             break;
                         case "SAY ":
                             string nick = GetPlayerNick(msg.SenderConnection);
                             string str = netStr.Substring(4);
                             WriteLine(nick + " : " + str);
                             SendToAll(nick, str);
                             break;
                         case "PRIV":
                             netStr = netStr.Substring(5);
                             string nickname = netStr.Substring(0, netStr.IndexOf(' '));
                             NetOutgoingMessage msg3 = server.CreateMessage();
                             NetConnection conn = GetPlayerConn(nickname);
                             if (conn != null)
                             {
                                 msg3.Write("PRIV");
                                 msg3.Write(GetPlayerNick(msg.SenderConnection));
                                 msg3.Write(netStr.Substring(nickname.Length));
                                 server.SendMessage(msg3, conn, NetDeliveryMethod.ReliableOrdered, 0);
                             }
                             break;
                         case "JOIN":
                             string game = netStr.Substring(5);
                             Player gamePlayer = GetPlayer(msg.SenderConnection);
                             string pnick = gamePlayer.Name;
                             WriteLine(pnick + " Joining : " + game);
                             NetOutgoingMessage msg4 = server.CreateMessage();
                             msg4.Write("GAMEJOIN");
                             Game playerGame = GetGame(game);
                             if (playerGame == null)
                             {
                                 playerGame = new Game(game);
                                 Games.Add(playerGame);
                             }
                             msg4.Write(game);
                             playerGame.Players.Add(gamePlayer);
                             playerGame.CurrentMap.GenerateMapPacket(msg4);
                             gamePlayer.Resources = 10000;
                             server.SendMessage(msg4, msg.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);
                             break;
                         default:
                             NetOutgoingMessage msg2 = server.CreateMessage();
                             msg2.Write("[Server] : Server Command not Found, You Wrote : " + netStr);
                             msg.SenderConnection.SendMessage(msg2, NetDeliveryMethod.ReliableOrdered);
                             break;
                     }
                     break;
                 case NetIncomingMessageType.StatusChanged:
                     ReadStatus(msg);
                     break;
                 case NetIncomingMessageType.ConnectionApproval:
                     WriteLine("New Client Connected from : " + msg.SenderEndpoint.ToString());
                     msg.SenderConnection.Approve();
                     SendToAll("[Server]", "New Client Connected");
                     Connections.Add(new Player("Player", msg.SenderConnection));
                     //SendFile("server_file.bin", msg.SenderConnection);
                     break;
                 default:
                     WriteLine("Can Not Pause Message Type: " + msg.MessageType.ToString());
                     break;
             }
         }
         Thread.Sleep(10);
     }
 }
Exemple #18
0
		public static void Start()
		{
			NetPeerConfiguration config = new NetPeerConfiguration("xnaapp");
			config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
			config.Port = 14242;

			// create and start server
			NetServer server = new NetServer(config);
			server.Start();

			// schedule initial sending of position updates
			double nextSendUpdates = NetTime.Now;

			// run until escape is pressed
			//while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
			while(true)
            {
				NetIncomingMessage msg;
				while ((msg = server.ReadMessage()) != null)
				{
					switch (msg.MessageType)
					{
						case NetIncomingMessageType.DiscoveryRequest:
							//
							// Server received a discovery request from a client; send a discovery response (with no extra data attached)
							//
							server.SendDiscoveryResponse(null, msg.SenderEndpoint);
							break;
						case NetIncomingMessageType.VerboseDebugMessage:
						case NetIncomingMessageType.DebugMessage:
						case NetIncomingMessageType.WarningMessage:
						case NetIncomingMessageType.ErrorMessage:
							//
							// Just print diagnostic messages to console
							//
							Console.WriteLine(msg.ReadString());
							break;
						case NetIncomingMessageType.StatusChanged:
							NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
							if (status == NetConnectionStatus.Connected)
							{
								//
								// A new player just connected!
								//
								Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");

								// randomize his position and store in connection tag
								msg.SenderConnection.Tag = new int[] {
									NetRandom.Instance.Next(10, 100),
									NetRandom.Instance.Next(10, 100)
								};
							}

							break;
						case NetIncomingMessageType.Data:
							//
							// The client sent input to the server
							//
							int xinput = msg.ReadInt32();
							int yinput = msg.ReadInt32();

							int[] pos = msg.SenderConnection.Tag as int[];

							// fancy movement logic goes here; we just append input to position
							pos[0] += xinput;
							pos[1] += yinput;
							break;
					}

					//
					// send position updates 30 times per second
					//
					double now = NetTime.Now;
					if (now > nextSendUpdates)
					{
						// Yes, it's time to send position updates

						// for each player...
						foreach (NetConnection player in server.Connections)
						{
							// ... send information about every other player (actually including self)
							foreach (NetConnection otherPlayer in server.Connections)
							{
								// send position update about 'otherPlayer' to 'player'
								NetOutgoingMessage om = server.CreateMessage();

								// write who this position is for
								om.Write(otherPlayer.RemoteUniqueIdentifier);

								if (otherPlayer.Tag == null)
									otherPlayer.Tag = new int[2];

								int[] pos = otherPlayer.Tag as int[];
								om.Write(pos[0]);
								om.Write(pos[1]);

								// send message
								server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
							}
						}

						// schedule next update
						nextSendUpdates += (1.0 / 30.0);
					}
				}

				// sleep to allow other processes to run smoothly
				Thread.Sleep(1);
			}

			server.Shutdown("app exiting");
		}
Exemple #19
0
        private static void StartNewRound(NetServer server)
        {
            Round theRound = NewRound();
            _drawer = theRound.Drawer.Name;
            _theWord = theRound.Word;
            NetOutgoingMessage newRoundMsg = server.CreateMessage();
            newRoundMsg.Write((byte) PacketTypes.Headers.NewRound);
            newRoundMsg.Write(theRound.Drawer.Name);
            server.SendToAll(newRoundMsg, NetDeliveryMethod.ReliableOrdered);

            NetOutgoingMessage drawerMsg = server.CreateMessage();
            drawerMsg.Write((byte) PacketTypes.Headers.WordMessage);
            drawerMsg.Write(theRound.Word);
            server.SendMessage(drawerMsg, theRound.Drawer.Connection, NetDeliveryMethod.ReliableOrdered);
            _theWord = theRound.Word;
            RoundTimer.Start();
        }
Exemple #20
0
        private static void HandleProtocol(NetIncomingMessage inc, byte packetheader, NetServer server)
        {
            switch ((PacketTypes.Headers) packetheader)
            {
                case PacketTypes.Headers.ReadyUpdate:
                    bool playerStatus = Convert.ToBoolean(inc.ReadString());
                    Player thePlayer = LookUpPlayer(inc.SenderConnection.RemoteUniqueIdentifier);

                    Console.WriteLine("Player {0} changed status to {1}", thePlayer.Name, playerStatus);
                    Players[inc.SenderConnection.RemoteUniqueIdentifier].ToggleReady();
                    NetOutgoingMessage msg = server.CreateMessage();
                    msg.Write((byte) PacketTypes.Headers.ReadyUpdate);
                    msg.Write(inc.SenderConnection.RemoteUniqueIdentifier);
                    msg.Write(playerStatus);
                    server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
                    break;
                case PacketTypes.Headers.LoggedIn:
                    string username = inc.ReadString();
                    Player newPlayer = NewPlayer(inc, server, username);
                    Console.WriteLine(Players.Count);
                    if (Players.Count == 0)
                    {
                        Console.WriteLine("Sending {0} host packet", newPlayer.Name);
                        NetOutgoingMessage hMessage = server.CreateMessage();
                        hMessage.Write((byte) PacketTypes.Headers.YouAreHost);
                        server.SendMessage(hMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                    }

                    Players.Add(inc.SenderConnection.RemoteUniqueIdentifier, newPlayer);
                    Players[inc.SenderConnection.RemoteUniqueIdentifier].Connection = inc.SenderConnection;
                    break;
                case PacketTypes.Headers.ChatSend:
                    if (Players[inc.SenderConnection.RemoteUniqueIdentifier].Name != _drawer)
                    {
                        NetOutgoingMessage chatMessageRelay = server.CreateMessage();
                        string chatM = inc.ReadString();
                        chatMessageRelay.Write((byte) PacketTypes.Headers.ChatReceive);
                        chatMessageRelay.Write(Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
                        chatMessageRelay.Write(chatM);
                        if (!_badwordList.Contains(chatM, StringComparer.OrdinalIgnoreCase))
                        {
                            server.SendToAll(chatMessageRelay, NetDeliveryMethod.ReliableOrdered);
                        }
                        if (String.Equals(chatM, _theWord, StringComparison.CurrentCultureIgnoreCase) & chatM != null)
                        {
                            NetOutgoingMessage someoneOne = server.CreateMessage();
                            someoneOne.Write((byte) PacketTypes.Headers.ChatReceive);
                            someoneOne.Write("Server");
                            someoneOne.Write(Players[inc.SenderConnection.RemoteUniqueIdentifier].Name
                                             + " has guessed the correct word being: " + _theWord);
                            server.SendToAll(someoneOne, NetDeliveryMethod.ReliableOrdered);
                            RoundTimer.Stop();
                            StartNewRound(server);
                        }
                    }
                    break;
                case PacketTypes.Headers.PictureUpdate:
                    int r = inc.ReadVariableInt32();
                    int g = inc.ReadVariableInt32();
                    int b = inc.ReadVariableInt32();
                    int x = inc.ReadVariableInt32();
                    int y = inc.ReadVariableInt32();
                    int size = inc.ReadVariableInt32();
                    NetOutgoingMessage msgPicture = server.CreateMessage();
                    msgPicture.Write((byte) PacketTypes.Headers.PictureUpdate);
                    msgPicture.WriteVariableInt32(r);
                    msgPicture.WriteVariableInt32(g);
                    msgPicture.WriteVariableInt32(b);
                    msgPicture.WriteVariableInt32(x);
                    msgPicture.WriteVariableInt32(y);
                    msgPicture.WriteVariableInt32(size);
                    server.SendToAll(msgPicture, NetDeliveryMethod.ReliableOrdered);
                    break;
                case PacketTypes.Headers.StartGame:
                    NetOutgoingMessage msgStart = server.CreateMessage();
                    msgStart.Write((byte) PacketTypes.Headers.StartGame);
                    server.SendToAll(msgStart, NetDeliveryMethod.ReliableOrdered);
                    RoundTimer.Enabled = true;
                    StartNewRound(server);
                    break;
                case PacketTypes.Headers.DrawLine:
                {
                    int r1 = inc.ReadVariableInt32();
                    int g1 = inc.ReadVariableInt32();
                    int b1 = inc.ReadVariableInt32();
                    int x1 = inc.ReadVariableInt32();
                    int y1 = inc.ReadVariableInt32();
                    int size1 = inc.ReadVariableInt32();
                    int x11 = inc.ReadVariableInt32();
                    int y11 = inc.ReadVariableInt32();
                    NetOutgoingMessage msgDrawLine = server.CreateMessage();
                    msgDrawLine.Write((byte) PacketTypes.Headers.DrawLine);
                    msgDrawLine.WriteVariableInt32(r1);
                    msgDrawLine.WriteVariableInt32(g1);
                    msgDrawLine.WriteVariableInt32(b1);
                    msgDrawLine.WriteVariableInt32(x1);
                    msgDrawLine.WriteVariableInt32(y1);
                    msgDrawLine.WriteVariableInt32(size1);
                    msgDrawLine.WriteVariableInt32(x11);
                    msgDrawLine.WriteVariableInt32(y11);
                    server.SendToAll(msgDrawLine, NetDeliveryMethod.ReliableOrdered);
                }
                    break;
            }
        }
        static void Main(string[] args)
        {
            IPEndPoint masterServerEndpoint = NetUtility.Resolve("localhost", CommonConstants.MasterServerPort);

            NetPeerConfiguration config = new NetPeerConfiguration("game");
            config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
            config.Port = 14242;

            NetServer server = new NetServer(config);
            server.Start();

            Console.WriteLine("Server started; waiting 5 seconds...");
            System.Threading.Thread.Sleep(5000);

            var lastRegistered = -60.0f;

            while(Console.KeyAvailable == false || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                // (re-)register periodically with master server
                if (NetTime.Now > lastRegistered + 60)
                {
                    // register with master server
                    NetOutgoingMessage regMsg = server.CreateMessage();
                    regMsg.Write((byte)MasterServerMessageType.RegisterHost);
                    IPAddress mask;
                    IPAddress adr = NetUtility.GetMyAddress(out mask);
                    regMsg.Write(server.UniqueIdentifier);
                    regMsg.Write(new IPEndPoint(adr, 14242));
                    Console.WriteLine("Sending registration to master server");
                    server.SendUnconnectedMessage(regMsg, masterServerEndpoint);
                    lastRegistered = (float)NetTime.Now;
                }

                NetIncomingMessage inc;
                while ((inc = server.ReadMessage()) != null)
                {
                    switch (inc.MessageType)
                    {
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            Console.WriteLine(inc.ReadString());
                            break;
                        case NetIncomingMessageType.Data:
                            // incoming chat message from a client
                            string chat = inc.ReadString();
                            Console.WriteLine(chat);
                            //Output("Broadcasting '" + chat + "'");

                            // broadcast this to all connections, except sender
                            List<NetConnection> all = server.Connections; // get copy
                            all.Remove(inc.SenderConnection);

                            if (all.Count > 0) {
                                NetOutgoingMessage om = server.CreateMessage();
                                om.Write(NetUtility.ToHexString(inc.SenderConnection.RemoteUniqueIdentifier) + " said: " + chat);
                                server.SendMessage(om, all, NetDeliveryMethod.ReliableOrdered, 0);
                            }
                            break;
                    }
                }

                System.Threading.Thread.Sleep(1);
            }

            Console.ReadKey();
        }
        public static void Main()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("xnaapp");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.Port = 14242;

            // create and start server
            NetServer server = new NetServer(config);
            server.Start();

            // schedule initial sending of position updates
            double nextSendUpdates = NetTime.Now;

            Dictionary<NetConnection, List<Damage>> damages = new Dictionary<NetConnection, List<Damage>>();
            Dictionary<NetConnection, Position> positions = new Dictionary<NetConnection, Position>();
            List<Npc> npcs = new List<Npc>();
            npcs.Add(new Npc { X = 1700, Y = 1000, Speed = 4, Life = 3 });

            // run until escape is pressed

            int i = 0;
            while (IsRunning)
            {
                NetIncomingMessage msg;
                while ((msg = server.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DiscoveryRequest:
                            //
                            // Server received a discovery request from a client; send a discovery response (with no extra data attached)
                            //
                            server.SendDiscoveryResponse(null, msg.SenderEndpoint);
                            break;
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            //
                            // Just print diagnostic messages to console
                            //
                            //Console.WriteLine(msg.ReadString());
                            Debug.WriteLine(msg.ReadString());
                            break;
                        case NetIncomingMessageType.StatusChanged:
                            NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                            if (status == NetConnectionStatus.Connected)
                            {
                                //
                                // A new player just connected!
                                //
                                Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");
                                Debug.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");
                                msg.SenderConnection.Tag = new object[6];
                            }

                            break;
                        case NetIncomingMessageType.Data:
                            //
                            // The client sent input to the server
                            //
                            MessageRouts messageRout = (MessageRouts)msg.ReadByte();
                            switch (messageRout)
                            {
                                case MessageRouts.Position:
                                    Position position = new Position();

                                    position.X = msg.ReadInt32();
                                    position.Y = msg.ReadInt32();
                                    position.Angle = msg.ReadInt32();
                                    position.IsShooting = msg.ReadBoolean();
                                    position.IsHuman = msg.ReadBoolean();

                                    positions[msg.SenderConnection] = position;
                                    break;
                                case MessageRouts.Fire:
                                    Damage damage = new Damage();

                                    damage.PlayerId = msg.ReadInt64();
                                    damage.WeaponId = msg.ReadByte();
                                    damage.Angle = msg.ReadByte();
                                    damage.X = msg.ReadInt32();
                                    damage.Y = msg.ReadInt32();

                                    if (damage.PlayerId > 50)
                                    {
                                        if (!damages.ContainsKey(msg.SenderConnection))
                                            damages[msg.SenderConnection] = new List<Damage>();

                                        damages[msg.SenderConnection].Add(damage);
                                    }
                                    else
                                    {
                                        npcs[(int)damage.PlayerId].Life -= 1;
                                        if (npcs[(int)damage.PlayerId].Life <= 0)
                                            npcs.RemoveAt((int)damage.PlayerId);
                                    }
                                    break;
                            }
                            break;
                    }

                    // send position updates 30 times per second
                    double now = NetTime.Now;
                    if (now > nextSendUpdates)
                    {
                        foreach (var position in positions.Values)
                        {
                            foreach (var npc in npcs)
                            {
                                float velX = position.X - npc.X;
                                float velY = position.Y - npc.Y;
                                float distance = (float)Math.Sqrt(Math.Pow(velX, 2) + Math.Pow(velY, 2));
                                if (distance < 300 && distance > 30)
                                {
                                    velX /= distance;
                                    velY /= distance;

                                    npc.X += (int)(velX * npc.Speed);
                                    npc.Y += (int)(velY * npc.Speed);

                                    NetOutgoingMessage om2 = server.CreateMessage();
                                    om2.Write((byte)MessageRouts.MoveNpc);
                                    om2.Write((byte)npcs.IndexOf(npc));
                                    om2.Write((int)npc.X);
                                    om2.Write((int)npc.Y);

                                    foreach (NetConnection player in server.Connections)
                                        server.SendMessage(om2, player, NetDeliveryMethod.ReliableUnordered);
                                }

                            }
                        }

                        foreach (NetConnection player in server.Connections)
                        {
                            foreach (var damagePair in damages)
                            {
                                if (damagePair.Key != player)
                                {
                                    foreach (var damage in damagePair.Value)
                                    {
                                        NetOutgoingMessage om2 = server.CreateMessage();
                                        om2.Write((byte)MessageRouts.Fire);
                                        om2.Write(damagePair.Key.RemoteUniqueIdentifier);
                                        om2.Write(damage.PlayerId);
                                        om2.Write(damage.WeaponId);
                                        om2.Write(damage.Angle);
                                        om2.Write(damage.X);
                                        om2.Write(damage.Y);

                                        server.SendMessage(om2, player, NetDeliveryMethod.ReliableUnordered);
                                    }
                                }
                            }

                            foreach (NetConnection otherPlayer in server.Connections)
                            {
                                if (player != otherPlayer)
                                {
                                    NetOutgoingMessage om = server.CreateMessage();

                                    if (positions.ContainsKey(otherPlayer))
                                    {
                                        om.Write((byte)MessageRouts.Position);
                                        om.Write(otherPlayer.RemoteUniqueIdentifier);
                                        om.Write(positions[otherPlayer].X);
                                        om.Write(positions[otherPlayer].Y);
                                        om.Write(positions[otherPlayer].Angle);
                                        om.Write(positions[otherPlayer].IsShooting);
                                        om.Write(positions[otherPlayer].IsHuman);
                                        server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                                    }

                                    // send message
                                }
                            }
                        }

                        foreach (var damageList in damages.Values)
                            damageList.Clear();

                        // schedule next update
                        nextSendUpdates += (1.0 / 30.0);
                    }
                }

                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }

            server.Shutdown("app exiting");
        }
Exemple #23
0
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("projectorigin");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.Port = 14242;

            // Create and start server
            NetServer server = new NetServer(config);
            server.Start();
            Console.WriteLine("Game Server starts");

            //Schedule initial sending of position updates
            double nextSendUpdates = NetTime.Now;

            GameStatus gameStatus = GameStatus.Initial;
            int clientDoneCounter = 0;

            //Generate a map and wait client to connect
            //InternalMap map = GenerateMap();
            int mapSeed = 1000;
            Random rand = new Random();
            mapSeed = rand.Next();
            //Run until escape is pressed
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                NetIncomingMessage msg;
                while ((msg = server.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DiscoveryRequest:
                            //
                            // Server received a discovery request from a client; send a discovery response (with no extra data attached)
                            //
                            NetOutgoingMessage com = server.CreateMessage();
                            //byte[] mapData = Serializer<InternalMap>.SerializeObject(map);
                            switch (server.ConnectionsCount)
                            {
                                case 0:
                                    com.Write((int)PlayerId.Green);
                                    com.Write((int)mapSeed); //Write map seed
                                    break;
                                case 1:
                                    com.Write((int)PlayerId.Red);
                                    com.Write((int)mapSeed); //Write map seed
                                    gameStatus = GameStatus.Receive;
                                    break;
                            }
                            server.SendDiscoveryResponse(com, msg.SenderEndpoint);
                            Console.WriteLine("Connect to: " + msg.SenderEndpoint);
                            break;
                        case NetIncomingMessageType.Data:
                            if (gameStatus == GameStatus.Receive)
                            {
                                //
                                // The client sent input to the server
                                //
                                IncomingMessageType imt = (IncomingMessageType)msg.ReadByte();
                                if (imt == IncomingMessageType.DataPlayerInfo)
                                {
                                    int wayPointCounter = msg.ReadInt32();

                                    List<PlayerInfo> wayPoints = new List<PlayerInfo>();
                                    for (int i = 1; i <= wayPointCounter; ++i)
                                    {
                                        Vector3 tempPos;
                                        tempPos.X = msg.ReadFloat();
                                        tempPos.Y = msg.ReadFloat();
                                        tempPos.Z = msg.ReadFloat();

                                        float tempOrientation;
                                        tempOrientation = msg.ReadFloat();

                                        PlayerInfo wayPoint = new PlayerInfo(tempPos, tempOrientation);
                                        wayPoints.Add(wayPoint);
                                    }
                                    playerInfoDict[msg.SenderEndpoint] = wayPoints;
                                    Console.WriteLine("Receive message from" + msg.SenderEndpoint);

                                    clientDoneCounter++;
                                    if (clientDoneCounter == 2)
                                        gameStatus = GameStatus.Sending;

                                }
                            }
                            break;
                    }

                    //
                    // send position updates 30 times per second
                    //
                    if (gameStatus == GameStatus.Sending)
                    {
                            // Yes, it's time to send position updates

                            // for each player...
                            foreach (NetConnection player in server.Connections)
                            {
                                if (!playerInfoDict.ContainsKey(player.RemoteEndpoint))
                                    playerInfoDict[player.RemoteEndpoint] = new List<PlayerInfo>();
                            }
                            foreach (NetConnection player in server.Connections)
                            {
                                //send information about every other player(not including self)
                                foreach (NetConnection otherPlayer in server.Connections)
                                {
                                    if (player.RemoteEndpoint == otherPlayer.RemoteEndpoint)
                                        continue;

                                    // send position update about 'otherPlayer' to 'player'
                                    NetOutgoingMessage om = server.CreateMessage();
                                    om.Write((byte)OutgoingMessageType.DataOtherPlayerInfo);

                                    om.Write(playerInfoDict[otherPlayer.RemoteEndpoint].Count);

                                    foreach (PlayerInfo playerInfo in playerInfoDict[otherPlayer.RemoteEndpoint])
                                    {
                                        om.Write(playerInfo.position.X);
                                        om.Write(playerInfo.position.Y);
                                        om.Write(playerInfo.position.Z);
                                        om.Write(playerInfo.orientation);
                                    }
                                    //send message
                                    server.SendMessage(om, player, NetDeliveryMethod.ReliableOrdered);
                                }

                            }

                            gameStatus = GameStatus.Receive;
                            clientDoneCounter = 0;

                        }
                }
            }

            server.Shutdown("server exiting");
        }
Exemple #24
0
		public static void Run()
		{
            // initialize
            int mapDimension = 16;
            Map mapServer = Map.GenerateShipsOnMap(new Map(mapDimension));
            Map mapHuman = Map.GenerateShipsOnMap(new Map(mapDimension));

            Player playerServer = new Player("Server", mapServer); // non-player-character ie our server
            Player playerHuman = new Player("Human", mapHuman); // player character
            int currentRound = 0;

            ArrayList sequences = initSequenceList("Scripts");
        

			NetPeerConfiguration config = new NetPeerConfiguration("xnaapp");
			config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
			config.Port = 14242;

			// create and start server
			NetServer server = new NetServer(config);
            try 
            {
			server.Start();

			// schedule initial sending of position updates
			double nextSendUpdates = NetTime.Now;

			// run until escape is pressed
			//while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            while (true)

            {
				NetIncomingMessage msg;
				while ((msg = server.ReadMessage()) != null)
				{
					switch (msg.MessageType)
					{
						case NetIncomingMessageType.DiscoveryRequest:
							// Server received a discovery request from a client; send a discovery response (with no extra data attached)
							server.SendDiscoveryResponse(null, msg.SenderEndpoint);
							break;
						case NetIncomingMessageType.VerboseDebugMessage:
						case NetIncomingMessageType.DebugMessage:
						case NetIncomingMessageType.WarningMessage:
						case NetIncomingMessageType.ErrorMessage:
							// Just print diagnostic messages to console
							Console.WriteLine(msg.ReadString());
							break;
						case NetIncomingMessageType.StatusChanged:
							NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
							if (status == NetConnectionStatus.Connected)
							{
								// A new player just connected!
								Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");

                                // create new player object
                                // initialize new game

                                //playerServer.startGame();
                                //playerHuman.startGame();

							}

							break;
						case NetIncomingMessageType.Data:

                            String responseString = "Nothing happend";

                            // player round

							// The client sent input to the server
							
                            String sequenceName = msg.ReadString();

                            int round = msg.ReadInt32();
                            if (round > currentRound)
                            {
                                currentRound = round;

                                if (sequences.Contains(sequenceName))
                                {
                                
                                // choose and fire sequence

                                var executer = new SequenceExecuter(playerServer.map);
                                var resultMessagePlayer = executer.LoadScript(sequenceName);


                                // switch round to npc

                                // fire random sequence
                                int randomIndex = RandomNumber(0, sequences.Count);
                                sequenceName = (String)sequences[randomIndex];
                                executer = new SequenceExecuter(playerHuman.map);
                                var resultMessageNPC = executer.LoadScript(sequenceName);

                                // send response to client

                                
                                String battlefield = Battlefield.Draw(playerHuman, playerServer);
                                responseString = "Player: " + resultMessagePlayer + "\n" + battlefield + " \nComputer: " + resultMessageNPC;
                                } else {
                                    responseString = "FireSequence not recognized!";
                                }
                            } else {
                                responseString = "Game round invalid";
                            }



                            NetOutgoingMessage om = server.CreateMessage();
                            om.Write(responseString);
                            // send to every player, which is only one in our case
                            foreach (NetConnection player in server.Connections)
                            {
                                server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                            }

							break;
					} // switch messageType

				} // while readMessage

               

				// sleep to allow other processes to run smoothly
				Thread.Sleep(1);
			} // while thread

            }
            catch (SocketException ex)
            {
                System.Console.WriteLine("Socket could not be initiated, is the port already used?!");
                System.Windows.Forms.MessageBox.Show("Socket could not be initiated, is the port already used?!", 
                    "September 1983 Server");
            }

		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="server"></param>
		void SendSnapshot ( NetServer server, SnapshotQueue queue, long serverTicks )
		{
			//	snapshot request is stored in connection's tag.s
			var debug	=	Game.Network.ShowSnapshots;
			var conns	=	server.Connections.Where ( c => c.IsSnapshotRequested() );

			var sw		=	new Stopwatch();

			foreach ( var conn in conns ) {

				sw.Reset();
				sw.Start();
					
				var frame		=	queue.LastFrame;
				var prevFrame	=	conn.GetRequestedSnapshotID();
				int size		=	0;
				var commandID	=	conn.GetLastCommandID();
				var snapshot	=	queue.Compress( ref prevFrame, out size);

				//	reset snapshot request :
				conn.ResetRequestSnapshot();

				var msg = server.CreateMessage( snapshot.Length + 4 * 4 + 8 + 1 );
			
				msg.Write( (byte)NetCommand.Snapshot );
				msg.Write( frame );
				msg.Write( prevFrame );
				msg.Write( commandID );
				msg.Write( serverTicks );
				msg.Write( snapshot.Length );
				msg.Write( snapshot ); 

				//	append atom table to first snapshot :
				if (commandID==0) {
					atoms.Write( msg );
				}

				//	Zero snapshot frame index means that client is waiting for first snapshot.
				//	and snapshot should reach the client.
				var delivery	=	prevFrame == 0 ? NetDeliveryMethod.ReliableOrdered : NetDeliveryMethod.UnreliableSequenced;

				if (prevFrame==0) {
					Log.Message("SV: Sending initial snapshot to {0}", conn.GetHailGuid().ToString() );
				}

				sw.Stop();

				server.SendMessage( msg, conn, delivery, 0 );

				if (debug) {
					Log.Message("Snapshot: #{0} - #{1} : {2} / {3} to {4} at {5} msec", 
						frame, prevFrame, snapshot.Length, size, conn.RemoteEndPoint.ToString(), sw.Elapsed.TotalMilliseconds );
				}
			}
		}
Exemple #26
0
        static void Main()
        {
            var connectedPlayers = 0;

            var config = new NetPeerConfiguration("romero");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.Port = 14242;

            var PlayerNames = new Dictionary<long, string>();

            //var xinput = 0;
            //var yinput = 0;
            var dummyName = string.Empty;
            float angle = 0;

            // create and start server
            var server = new NetServer(config);
            server.Start();
            Console.WriteLine("Server online");

            // schedule initial sending of position updates
            var nextSendUpdates = NetTime.Now;

            // run until escape is pressed
            while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                NetIncomingMessage msg;
                while ((msg = server.ReadMessage()) != null)
                {


                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DiscoveryRequest:
                            //
                            // Server received a discovery request from a client; send a discovery response (with no extra data attached)
                            //
                            var om = server.CreateMessage();

                            if (connectedPlayers < 4)
                            {
                                om.Write(true);
                                server.SendDiscoveryResponse(om, msg.SenderEndpoint);

                            }
                            else
                            {
                                om.Write(false);
                                server.SendDiscoveryResponse(om, msg.SenderEndpoint);
                            }

                            break;
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.ErrorMessage:
                            //
                            // Just print diagnostic messages to console
                            //
                            Console.WriteLine(msg.ReadString());
                            break;
                        case NetIncomingMessageType.StatusChanged:
                            var status = (NetConnectionStatus)msg.ReadByte();

                            if (status == NetConnectionStatus.Connected)
                            {
                                //
                                // A new player just connected!
                                //

                                Console.WriteLine(msg.SenderConnection.RemoteUniqueIdentifier + " connected. (IP Address: " + msg.SenderEndpoint.Address + ")");
                                connectedPlayers++;
                                Console.WriteLine(connectedPlayers + " players ingame");
                            };

                            if (status == NetConnectionStatus.Disconnected)
                            {
                                Console.WriteLine(msg.SenderConnection.RemoteUniqueIdentifier + " disconnected. (IP Address: " + msg.SenderEndpoint.Address + ")");
                                connectedPlayers--;
                                Console.WriteLine(connectedPlayers + " players ingame");
                            }


                            break;
                        case NetIncomingMessageType.Data:
                            //
                            // The client sent input to the server
                            //

                            dummyName = msg.ReadString();
                            if (!PlayerNames.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
                            {
                                  PlayerNames.Add(msg.SenderConnection.RemoteUniqueIdentifier, dummyName);
                            }
                          

                            // fancy movement logic goes here

                            var xinput = msg.ReadInt32();
                            var yinput = msg.ReadInt32();
                            var playerAngle = msg.ReadFloat();

                            var pos = msg.SenderConnection.Tag as float[];

                            if (pos != null)
                            {
                                pos[0] = xinput;
                                pos[1] = yinput;
                                pos[2] = playerAngle;
                            }


                            break;

                    }

                    //
                    // send position updates 60 times per second
                    //
                    var now = NetTime.Now;
                    if (now > nextSendUpdates)
                    {
                        // Yes, it's time to send position updates

                        // for each player...


                        foreach (var player in server.Connections)
                        {
                            // ... send information about every other player (actually including self)
                            foreach (var otherPlayer in server.Connections)
                            {
                                // send position update about 'otherPlayer' to 'player'
                                var om = server.CreateMessage();
                                if (otherPlayer != null)
                                {
                                    // write who this position is for
                                    om.Write(otherPlayer.RemoteUniqueIdentifier);
                                    if (PlayerNames.ContainsKey(otherPlayer.RemoteUniqueIdentifier))
                                    {
                                        om.Write(PlayerNames.Single(i => i.Key == otherPlayer.RemoteUniqueIdentifier).Value);
                                    }


                                    if (otherPlayer.Tag == null)
                                        otherPlayer.Tag = new float[3];

                                    var pos = otherPlayer.Tag as float[];

                                    om.Write(pos[0]);
                                    om.Write(pos[1]);
                                    om.Write(pos[2]);

                                    // send message
                                    server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
                                }

                            }
                        }

                        // schedule next update
                        nextSendUpdates += (1.0 / 60.0);
                    }
                }

                // sleep to allow other processes to run smoothly
                Thread.Sleep(1);
            }
            Console.WriteLine("Server powering down..");
            server.Shutdown("bye");
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="server"></param>
		void SendNotifications ( NetServer server )
		{
			List<string> messages;
			lock (notifications) {
				messages = notifications.ToList();
				notifications.Clear();
			}

			var conns = server.Connections;

			if (!conns.Any()) {
				return;
			}

			foreach ( var message in messages ) {
				var msg = server.CreateMessage( message.Length + 1 );
				msg.Write( (byte)NetCommand.Notification );
				msg.Write( message );
				server.SendMessage( msg, conns, NetDeliveryMethod.ReliableSequenced, 0 );
			}
		}