Page 139 - CSharp/C#
P. 139

{
                   public static List<Client> Clients = new List<Client>();

                   public static void AddClient(Socket socket)
                   {
                       Clients.Add(new Client(socket,Clients.Count));
                   }

                   public static void RemoveClient(int id)
                   {
                       Clients.RemoveAt(Clients.FindIndex(x => x.Id == id));
                   }
               }


              Client Side example


        Connecting to server


        First of all we want to create a class what connects to the server te name we give it is: Connector:


         class Connector
         {
             private Socket _connectingSocket;
         }


        Next Method for this class is TryToConnect()


        This method goth a few interestin things:

            1.  Create the socket;

            2.  Next I loop until the socket is connected


            3.  Every loop it is just holding the Thread for 1 second we don't want to DOS the server XD


            4.  With Connect() it will try to connect to the server. If it fails it will throw an exception but the
              wile will keep the program connecting to the server. You can use a Connect CallBack
              method for this, but I'll just go for calling a method when the Socket is connected.

            5.  Notice the Client is now trying to connect to your local pc on port 1234.


                public void TryToConnect()
                {
                    _connectingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
               ProtocolType.Tcp);

                     while (!_connectingSocket.Connected)
                     {
                         Thread.Sleep(1000);

                         try
                         {
                             _connectingSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),
               1234));
                         }




        https://riptutorial.com/                                                                               85
   134   135   136   137   138   139   140   141   142   143   144