/// <summary> /// This is the heart of the server code. It startse a TCP listener for new connections and passes the listener, /// along with the callMe function, to BeginAcceptSocket as the state parameter. Upon a connection request coming /// in the OS invokes the AcceptNewClient as the callback method. /// </summary> /// <param name="callMe"></param> public static void ServerAwaitingClientLoop(Delegate callMe) { TcpListener listener = new TcpListener(IPAddress.Any, DEFAULT_PORT); HostRequest clientRequest = new HostRequest(listener, callMe); listener.Start(); listener.BeginAcceptSocket(AcceptNewClient, clientRequest); }
/// <summary> /// This is the callback that BeginAcceptSocket uses. It performs the following operations: /// /// 1. Extracts the state containing the TcpListener and the callMe delegate from "ar" /// 2. Creates a new socket with by using listener.EndAcceptSocket /// 3. Saves the socket in a new SocketState /// 4. Calls the callMe method and pass it the new SocketState /// 5. Awaits a new connection request (continue the event loop) with BeginAcceptSocket. /// </summary> /// <param name="ar"></param> public static void AcceptNewClient(IAsyncResult ar) { // Extracts the state. HostRequest request = (HostRequest)ar.AsyncState; // Creates a new socket. Socket s = request.Listener.EndAcceptSocket(ar); // Saves the socket in a SocketState. SocketState state = new SocketState(s); // Calls the callMe method. request.CallMe(state); // Awaits a new connection request. request.Listener.BeginAcceptSocket(AcceptNewClient, request); }