Exemplo n.º 1
0
 /// <summary>
 /// Listens for new connections to the Server.
 /// </summary>
 /// <param name="result">Contains the port to listen in the AsyncState object.</param>
 private void ListenForConnections(int port)
 {
     using (Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         try
         {
             listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
             listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
             listener.Bind(new IPEndPoint(Information.IP, port));
             listener.Listen(100);
             while (Active)
             {
                 try
                 {
                     if (listener.Poll(0, SelectMode.SelectRead) && !Pausing)
                     {
                         ClientObject client = new ClientObject();
                         client.Connections.Add("Main", new Connection(listener.Accept(), true, new Thread(() => HandleClient(client))));
                         if (Authenticate(client))
                         {
                             client.Connections["Main"].StartHandler();
                         }
                         else
                         {
                             client.Dispose();
                         }
                     }
                     else
                     {
                         Thread.Sleep(0);
                     }
                 }
                 catch (ThreadInterruptedException) { break; }
                 catch (Exception error) { Debug.WriteLine($"'{error.GetType()}' thrown in thread {Thread.CurrentThread.ManagedThreadId}. Message: {error.Message}"); }
             }
         }
         catch (Exception error) { Debug.WriteLine($"'{error.GetType()}' thrown in thread {Thread.CurrentThread.ManagedThreadId}. Message: {error.Message}"); }
     }
 }