/// <summary> /// Gets initial data from the client, more specifically the player name. Sends initial game info to the client. /// </summary> /// <param name="state"></param> private static void ReceivePlayerName(SocketState state) { try { // This block splits up the server data within the StringBuilder, and places it into initialInfo. StringBuilder sb = state.sb; char[] separator = new char[] { '\n' }; string[] initialInfo = sb.ToString().Split(separator, StringSplitOptions.RemoveEmptyEntries); // Assigns the ID sent by the server to the socket state for uniqie identification of connections. state.sb.Remove(0, initialInfo[0].Length + 1); string name = initialInfo[0]; Ship newShip; lock (theWorld) { newShip = theWorld.AddShipRandomPosition(name, settings.GetShotDelay(), settings.GetThrustStrength(), settings.GetTurningRate(), settings.GetStartingHP(), settings.GetShipHitBoxSize()); } state.ClientCallback = HandleClientRequest; state.ID = newShip.GetID(); Networking.SendSocket(state.theSocket, "" + newShip.GetID() + "\n" + theWorld.GetSize() + "\n"); lock (clients) { clients.AddLast(state); } Networking.GetData(state); } catch (Exception e) { Console.WriteLine("EXCEPTION: " + e.Message); } }
/// <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(); } }