Program.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Text;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. namespace Lab20ServerMultiThread
  7. {
  8. class Program
  9. {
  10. public static void Main(string[] args)
  11. {
  12. TcpListener server = null;
  13. try
  14. {
  15. // Threading..
  16. int maxThreadCount = Environment.ProcessorCount * 4;
  17. ThreadPool.SetMaxThreads(maxThreadCount, maxThreadCount);
  18. ThreadPool.SetMinThreads(2, 2);
  19. // Server creation
  20. int port = 9999;
  21. int counter = 0;
  22. IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  23. server = new TcpListener(localAddr, port);
  24. server.Start();
  25. Console.WriteLine($"Server started on 127.0.0.1:{port}. Thread count: {maxThreadCount}");
  26. // Listining for clients
  27. while (true)
  28. {
  29. Console.WriteLine("Waiting for connection...");
  30. ThreadPool.QueueUserWorkItem(ClientProcessing, server.AcceptTcpClient());
  31. Console.WriteLine($"Accepted connection #{counter}");
  32. counter++;
  33. }
  34. }
  35. catch (SocketException exc)
  36. {
  37. Console.WriteLine($"Socket exception: {exc}");
  38. }
  39. finally
  40. {
  41. server.Stop();
  42. }
  43. }
  44. /// <summary>
  45. /// Processes accepted client
  46. /// </summary>
  47. /// <param name="state">State.</param>
  48. private static void ClientProcessing(object state)
  49. {
  50. byte[] bytes = new byte[256];
  51. string data = null;
  52. TcpClient tcpClient = state as TcpClient;
  53. // Get incoming info
  54. NetworkStream stream = tcpClient.GetStream();
  55. int i;
  56. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  57. {
  58. data = Encoding.ASCII.GetString(bytes, 0, i).ToUpper();
  59. // Echo uppered info
  60. byte[] msg = Encoding.ASCII.GetBytes(data);
  61. stream.Write(msg, 0, msg.Length);
  62. }
  63. tcpClient.Close();
  64. }
  65. }
  66. }