development:csharp:multithreaded_tcp_listener

Multithreaded TCP listener in C#

static TcpListener server;
Int32 port = 8889;
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
server = new TcpListener(localAddr, port);
ThreadPool.QueueUserWorkItem(ConnectionServer, server);
 
private static void ConnectionServer(object obj)
{
  var server = (TcpListener)obj;
  try
  {
    server.Start();
    while (true)
    {
      TcpClient tcpclient = server.AcceptTcpClient();
      ThreadPool.QueueUserWorkItem(ConnectionProcessor, tcpclient);
    }
  }
  catch (SocketException e)
  {
    Console.WriteLine("SocketException: {0}", e);
  }
  finally
  {
    server.Stop();
  }
}
 
private static void ConnectionProcessor(object obj)
{
  var server= (TcpClient)obj;
  Byte[] bytes1 = new Byte[132];
  NetworkStream stream = server.GetStream();
  while (stream.Read(bytes1, 0, bytes1.Length) != 0)
  {
    // do something with bytes
    // respond perhaps?
    stream.Write(newBytes, 0, newBytes.Length);
  }
  server.Close();
}   
  • development/csharp/multithreaded_tcp_listener.txt
  • Last modified: 2021/05/19 12:23
  • by 127.0.0.1