public ClientConnectedEventArgs(ClientInstance client) { Client = client; }
// Connection request on listening socket // This method must do its work quickly, since it blocks other incoming connections. public void OnClientConnected(IAsyncResult ar) { try { var clientSocket = listenerSocket.EndAccept(ar); var client = new ClientInstance(clientSocket, nextClientId++); lock (clientInstances) { clientInstances.Add(client); } // Start accepting connections again. listenerSocket.BeginAccept(new AsyncCallback(OnClientConnected), listenerSocket); if (ClientConnected != null) { ClientConnected(this, new ClientConnectedEventArgs(client)); } } catch (ObjectDisposedException) { Console.WriteLine("OnClientConnected: Socket has been closed\n"); } catch (SocketException se) { Console.WriteLine("OnClientConnected: Exception: \n" + se.Message); } // Note: when exception is thrown, server will stop accepting new connections! // Also, when closing the listening socket, this method will automatically be triggered, and the ObjectDisposedException will be thrown in EndAccept, this is normal. }