// Callback to accept a new connection
private void ProcessingThread()
{
while (true)
{
// Accept incoming connections
if (listener.Pending())
{
Socket s = listener.AcceptSocket();
RemoteClient rc = new RemoteClient(s);
clients.Add(rc);
General.WriteLogLine("Remote client " + rc + " connected.");
}
// Process clients
for (int i = clients.Count - 1; i >= 0; i--)
{
RemoteClient rc = clients[i];
try
{
// Process the client. This will call ProcessCommand for any incoming commands.
if (!rc.Process(this))
{
// Connection lost.
DisconnectClient(rc, null);
}
}
catch (InvalidDataException e)
{
// Invalid data received
DisconnectClient(rc, "Client sent invalid protocol data; " + e.Message);
}
catch (SocketException e)
{
switch (e.SocketErrorCode)
{
// This exception simply means there is no data to read.
// Check if the client is timing out (then disconnect).
case SocketError.WouldBlock:
if (rc.CheckTimeout())
{
DisconnectClient(rc, "Connection timed out.");
}
break;
// Some unknown exception
default:
DisconnectClient(rc, SocketErrorDesc.GetDesc(e.SocketErrorCode) + " (" + e.SocketErrorCode + ")");
break;
}
}
catch (Exception e)
{
// This is horrible
DisconnectClient(rc, "Client caused " + e.GetType().Name + ": " + e.Message);
}
}
// Process services
foreach (KeyValuePair <string, RemoteService> svc in services)
{
svc.Value.UpdateNetworkThread();
}
// Sleep
try { Thread.Sleep(2); }
catch (ThreadInterruptedException e) { return; }
}
}