public void SocketState_GetAndSetID() { // create a socket using to pass to a SocketState object Network.MakeSocket("localhost", out Socket sock, out IPAddress address); try { SocketState state = new SocketState(sock, -1); // ID should be same as what it was set when object was created Assert.AreEqual(-1, state.GetID()); // check that setting id changes what is stored state.SetID(5); Assert.AreEqual(5, state.GetID()); } // make sure we close the socket when we are done testing our state finally { sock.Dispose(); } }
/// <summary> /// NetworkAction delegate which implements the server's part of the /// initial handshake. /// /// Creates a new Ship with the given name and a new unique ID and sets /// the SocketState's ID. /// /// Changes the state's callback method to one that handles command /// requests from the client then asks the clients for data. /// </summary> private void ReceivePlayerName(SocketState state) { // enumerate the complete received messages. IEnumerable <string> messages = GetTokens(state.GetStringBuilder()); // find the name in the complete messages string playerName = ""; if (messages.Any()) { playerName = messages.First(); state.GetStringBuilder().Clear(); } // if there wasn't a complete message continue the event loop else { Network.GetData(state); return; } // the id and world are being changed by callback methods (different threads) int playerID = 0; lock (world) { playerID = IDCounter++; // make a ship with a the name and give it a unique id // add ship to world world.MakeNewShip(playerName.TrimEnd(), playerID); // set the socket state ID state.SetID(playerID); } if (state.HasError) { HandleNetworkError(state); return; } // change the callback to handle incoming commands from the client state.SetNetworkAction(HandleClientCommands); // send the startup info to the client (ID and world size) string startupInfo = playerID + "\n" + world.GetSize() + "\n"; Network.Send(state.GetSocket(), startupInfo); // set FirstPlayerHasJoined to true if this is the first player and // get the start time if (!FirstPlayerHasJoined) { FirstPlayerHasJoined = true; // set the start time to now (current value will be server start time) startTime = DateTime.UtcNow; } // handshake is done print line that someone has connected Console.Out.WriteLine("A new Client has contacted the Server."); // add the client's socket to a set of all clients lock (clients) { clients.Add(state); } // ask the client for data (continue loop) Network.GetData(state); }