title: C# Async Sockets - Thread Logic
body: <p>How does the thread creation logic behind Socket.BeginSend, Socket.BeginReceive, Socket.BeginAccept, etc. works?</p>
  
  <p>Is it going to create a new thread for each client that connects to my server to handle the code, or is it only going to create one thread for each function(accept, receive, send...) no mattering how many clients there are connected to the server? This way only executing the client 2 accept code once the client 1 accept code is completed and so on.</p>
  
  <p>This is the code I made and I am trying to understand the logic behind it better:</p>
  
  <pre><code>public class SocketServer
  {
      Socket _serverSocket;
      List&lt;Socket&gt; _clientSocket = new List&lt;Socket&gt;();
      byte[] _globalBuffer = new byte[1024];
  
      public SocketServer()
      {
          _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      }
  
      public void Bind(int Port)
      {
          Console.WriteLine("Setting up server...");
          _serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, Port));
      }
  
      public void Listen(int BackLog)
      {
          _serverSocket.Listen(BackLog);
      }
  
      public void Accept()
      {
          _serverSocket.BeginAccept(AcceptCallback, null);
      }
  
      private void AcceptCallback(IAsyncResult AR)
      {
          Socket socket = _serverSocket.EndAccept(AR);
          _clientSocket.Add(socket);
          Console.WriteLine("Client Connected");
          socket.BeginReceive(_globalBuffer, 0, _globalBuffer.Length, SocketFlags.None, ReceiveCallback, socket);
          Accept();
      }
  
      private void ReceiveCallback(IAsyncResult AR)
      {
          Socket socket = AR.AsyncState as Socket;
          int bufferSize = socket.EndReceive(AR);
  
          string text = Encoding.ASCII.GetString(_globalBuffer, 0, bufferSize);
          Console.WriteLine("Text Received: {0}", text);
  
          string response = string.Empty;
  
          if (text.ToLower() != "get time")
              response = $"\"{text}\" is a Invalid Request";
          else
              response = DateTime.Now.ToLongTimeString();
  
          byte[] data = Encoding.ASCII.GetBytes(response);
          socket.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallback, socket);
  
          socket.BeginReceive(_globalBuffer, 0, _globalBuffer.Length, SocketFlags.None, ReceiveCallback, socket);
      }
  
      private void SendCallback(IAsyncResult AR)
      {
          (AR.AsyncState as Socket).EndSend(AR);
      }
  }
  </code></pre>