Example #1
0
        protected virtual void OnRaiseClientConnectedEvent(ClientConnectedEventArgs e)
        {
            EventHandler <ClientConnectedEventArgs> handler = RaiseClientConnectedEvent;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Example #2
0
        public async void StartListeningForIncomingConnection(IPAddress ipaddr = null, int port = 50000)
        // I need the async keyword in the method declare as I will be making an async call within it
        // I am changing this to start two listeners at once
        {
            if (ipaddr == null)
            {
                ipaddr = IPAddress.Any;
            }
            if (port <= 0 || port >= 65535)
            {
                port = 50000;
            }
            myIP   = ipaddr;
            myPort = port;

            System.Diagnostics.Debug.WriteLine(string.Format($"IP Address: {ipaddr}  - Port: {port} "));
            // since we are using.System Diagnostics we can skip the System.Diagnostics bit really

            myTCPListener = new TcpListener(myIP, myPort);

            try
            {
                myTCPListener.Start();

                KeepRunning = true;
                while (KeepRunning)
                {
                    var returnedByAccept = await myTCPListener.AcceptTcpClientAsync();


                    myTcpClients.Add(returnedByAccept);
                    //so if a new Tcp Client connects we add them to our Tcp Client List. . . .
                    // I would like to do something with aliases here, tp refer correctly to each client
                    Debug.WriteLine(string.Format($"Client connected successfully, count" +
                                                  $" {myTcpClients.Count} - {returnedByAccept.Client.RemoteEndPoint}"
                                                  ));

                    TakeCareOfTCPClient(returnedByAccept);

                    ClientConnectedEventArgs eaClientConnected;
                    eaClientConnected = new ClientConnectedEventArgs(
                        returnedByAccept.Client.RemoteEndPoint.ToString()
                        );
                    OnRaiseClientConnectedEvent(eaClientConnected);
                }
            }
            catch (Exception excp)
            {
                Debug.WriteLine(excp.ToString());
            }
        }