in UnityProject/Assets/Scripts/Server/Server.cs [465:549]
public void Update()
{
// Are there any new connections pending?
if (listener.Pending())
{
System.Console.WriteLine("Client pending..");
TcpClient client = listener.AcceptTcpClient();
client.NoDelay = true; // Use No Delay to send small messages immediately. UDP should be used for even faster messaging
System.Console.WriteLine("Client accepted.");
// We have a maximum of 2 clients per game
if(this.clients.Count < Server.maxPlayers)
{
// Add client and give it the Id of the value of rollingPlayerId
this.clients.Add(client, this.server.rollingPlayerId);
this.server.rollingPlayerId++;
return;
}
else
{
// game already full, reject the connection
try
{
SimpleMessage message = new SimpleMessage(MessageType.Reject, "game already full");
NetworkProtocol.Send(client, message);
}
catch (SocketException) { }
}
}
// Iterate through clients and check if they have new messages or are disconnected
int playerIdx = 0;
foreach (var client in this.clients)
{
var tcpClient = client.Key;
try
{
if (tcpClient == null) continue;
if (this.IsSocketConnected(tcpClient) == false)
{
System.Console.WriteLine("Client not connected anymore");
this.clientsToRemove.Add(tcpClient);
}
var messages = NetworkProtocol.Receive(tcpClient);
foreach(SimpleMessage message in messages)
{
System.Console.WriteLine("Received message: " + message.message + " type: " + message.messageType);
bool disconnect = HandleMessage(playerIdx, tcpClient, message);
if (disconnect)
this.clientsToRemove.Add(tcpClient);
}
}
catch (Exception e)
{
System.Console.WriteLine("Error receiving from a client: " + e.Message);
this.clientsToRemove.Add(tcpClient);
}
playerIdx++;
}
//Remove dead clients
foreach (var clientToRemove in this.clientsToRemove)
{
try
{
this.RemoveClient(clientToRemove);
}
catch (Exception e)
{
System.Console.WriteLine("Couldn't remove client: " + e.Message);
}
}
this.clientsToRemove.Clear();
//End game if no clients
if(this.server.GameStarted())
{
if(this.clients.Count <= 0)
{
System.Console.WriteLine("Clients gone, stop session");
this.TerminateGameSession();
}
}
}