// now we declare the method to raise the above event // of course we will need to prepare and pass it the event arguments that will be sent to all its subscribers // we have declared it as protected virtual so that any derived classes can override the event invocation behavior protected virtual void RaiseClientConnectedEvent(ClientConnectedEventArgs e) { // within this method we are creating a temporary copy of the EventHandler object to avoid any race conditions EventHandler <ClientConnectedEventArgs> custom_event = ClientConnectedEvent; if (custom_event != null) { // here Object sender will point to custom_event which is an instance of ClientConnectedEvent event custom_event(this, e); } }
// now we will create a method for listener public async void StartListeningForIncomingConnection(IPAddress ipaddr = null, int port = 23000) { //some sanity check code if (ipaddr == null) { ipaddr = IPAddress.Any; } if (port <= 0) { port = 23000; } //lets store the user supplied IPAddress and port number in instance variables mIP = ipaddr; mPort = port; //some disgnostics System.Diagnostics.Debug.WriteLine(string.Format("IP Address: {0} - Port: {1}", mIP.ToString(), mPort)); mTcpListener = new TcpListener(mIP, mPort); try { mTcpListener.Start(); // following is to continuously accept client connections KeepRunning = true; while (KeepRunning) { // in order to accept incoming connections, we need to call another method AcceptTcpClientAsync // this method returns a TcpClient object. TcpClient is yet another helper class that allows us to // handle client sockets in an easy fashion var returnedByAccept = await mTcpListener.AcceptTcpClientAsync(); // add the new client to our list mClients.Add(returnedByAccept); Debug.WriteLine("Client connected successfully, count: {0} - {1}", mClients.Count, returnedByAccept.Client.RemoteEndPoint); TakeCareOfTcpClient(returnedByAccept); // now we will raise the event that a new client has connected // prepare the event args ClientConnectedEventArgs eaClientConnected = new ClientConnectedEventArgs(returnedByAccept.Client.RemoteEndPoint.ToString()); // now we raise the event RaiseClientConnectedEvent(eaClientConnected); } } catch (Exception e) { Debug.WriteLine(e.ToString()); } }
void HandleClientConnected(Object sender, ClientConnectedEventArgs ccea) { txtConsole.AppendText(string.Format("{0} - New Client connected {1}{2}", DateTime.Now, ccea.NewClient, Environment.NewLine)); }