MichaelW

Untitled

Sep 29th, 2012
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. Object kritiskSektion = new Object();
  2. bool aktiv = true;
  3.  
  4.      
  5. public static void DoBeginAcceptTcpClient()
  6.             {
  7.                 while (aktiv)
  8.                 {
  9.                     // Set the event to nonsignaled state.
  10.                     tcpClientConnected.Reset();
  11.      
  12.                     // Start to listen for connections from a client.
  13.                     Console.WriteLine("Waiting for a connection...");
  14.      
  15.                     // Accept the connection.  
  16.                     // BeginAcceptSocket() creates the accepted socket.
  17.                     server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback),
  18.                                                  server);
  19.      
  20.                     // Wait until a connection is made and processed before  
  21.                     // continuing.
  22.                     tcpClientConnected.WaitOne();
  23.                 }
  24.             }
  25.      
  26.            
  27.             public static void DoAcceptTcpClientCallback(IAsyncResult ar)
  28.             {
  29.                
  30.                 Console.WriteLine("DoAcceptTcpClientCallback started");
  31.                 // Get the listener that handles the client request.
  32.                 TcpListener listener = (TcpListener)ar.AsyncState;
  33.      
  34.                 TcpClient client = listener.EndAcceptTcpClient(ar);
  35.      
  36.                 // Lock clientList from other threads and add the new client to it
  37.                 lock (kritiskSektion)
  38.                 {
  39.                     clientList.Add(client);
  40.                 }
  41.      
  42.                 // Process the connection here. (Add the client to a
  43.                 // server table, read data, etc.)
  44.                 Console.WriteLine("Client connect completed");
  45.      
  46.                 // Signal the calling thread to continue.
  47.                 tcpClientConnected.Set();
  48.             }
  49.      
  50.             // Bliver kaldt når brugeren lukker programmet
  51.             static public void Close()
  52.             {
  53.      
  54.         aktiv = false;
  55.                 acceptClientsThread.Abort();
  56.                
  57.                 server.Stop();
  58.                
  59.                
  60.      
  61.             }
Advertisement
Add Comment
Please, Sign In to add comment