Exemplo n.º 1
0
        /// <summary>
        /// The main function driving the server almost entirely. Updates the world, then gets each object's info,
        /// adds it to the data to be sent to the clients, then sends it to all the clients.
        /// Any disconnected clients are also removed/dealt with.
        /// </summary>
        private static void Update()
        {
            if (watch.IsRunning)
            {
                // Make thread wait until the frame delay is met.
                while (watch.ElapsedMilliseconds < settings.GetMSPerFrame())
                {
                    Thread.Yield();
                }

                watch.Restart();

                // Update the world, and sent it as one to all clients.
                lock (theWorld)
                {
                    theWorld.Update();
                    foreach (Ship ship in theWorld.GetShips().Values)
                    {
                        gameData.Append(ship.ToString() + "\n");
                    }
                    foreach (Projectile proj in theWorld.GetProjectiles().Values)
                    {
                        gameData.Append(proj.ToString() + "\n");
                    }
                    foreach (Star star in theWorld.GetStars().Values)
                    {
                        gameData.Append(star.ToString() + "\n");
                    }
                    theWorld.Cleanup();
                }

                // Iterate through the linked list of clients in order to remove any disconnected clients.
                lock (clients)
                {
                    LinkedListNode <SocketState> firstNode = clients.First;
                    while (firstNode != null)
                    {
                        SocketState socketState = firstNode.Value;
                        Networking.SendSocket(socketState.theSocket, gameData.ToString());
                        if (!socketState.theSocket.Connected)
                        {
                            lock (theWorld)
                            {
                                if (theWorld.GetShips().ContainsKey(socketState.ID))
                                {
                                    theWorld.GetShips()[socketState.ID].MakeInactive();
                                }
                            }
                            LinkedListNode <SocketState> nextNode = firstNode.Next;
                            clients.Remove(firstNode);
                            firstNode = nextNode;
                        }
                        else
                        {
                            firstNode = firstNode.Next;
                        }
                    }
                }

                gameData.Clear();
            }
        }