12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- using System;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace Lab20ServerMultiThread
- {
- class Program
- {
- public static void Main(string[] args)
- {
- TcpListener server = null;
- try
- {
- // Threading..
- int maxThreadCount = Environment.ProcessorCount * 4;
- ThreadPool.SetMaxThreads(maxThreadCount, maxThreadCount);
- ThreadPool.SetMinThreads(2, 2);
- // Server creation
- int port = 9999;
- int counter = 0;
- IPAddress localAddr = IPAddress.Parse("127.0.0.1");
- server = new TcpListener(localAddr, port);
- server.Start();
- Console.WriteLine($"Server started on 127.0.0.1:{port}. Thread count: {maxThreadCount}");
- // Listining for clients
- while (true)
- {
- Console.WriteLine("Waiting for connection...");
- ThreadPool.QueueUserWorkItem(ClientProcessing, server.AcceptTcpClient());
- Console.WriteLine($"Accepted connection #{counter}");
- counter++;
- }
- }
- catch (SocketException exc)
- {
- Console.WriteLine($"Socket exception: {exc}");
- }
- finally
- {
- server.Stop();
- }
- }
- /// <summary>
- /// Processes accepted client
- /// </summary>
- /// <param name="state">State.</param>
- private static void ClientProcessing(object state)
- {
- byte[] bytes = new byte[256];
- string data = null;
- TcpClient tcpClient = state as TcpClient;
- // Get incoming info
- NetworkStream stream = tcpClient.GetStream();
- int i;
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- data = Encoding.ASCII.GetString(bytes, 0, i).ToUpper();
- // Echo uppered info
- byte[] msg = Encoding.ASCII.GetBytes(data);
- stream.Write(msg, 0, msg.Length);
- }
- tcpClient.Close();
- }
- }
- }
|