Advertisement
Zakkq

C# Tcp Server Thread Handling

May 22nd, 2014
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9.  
  10. namespace Server
  11. {
  12.    
  13.     class Server
  14.     {
  15.         bool running = true;
  16.         int clients = 0;
  17.         public void Start()
  18.         {
  19.             //Accept connections
  20.             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  21.             IPEndPoint endpoint = new IPEndPoint(new IPAddress(0x0100007f), 5678); //127.0.0.1
  22.             socket.Bind(endpoint);
  23.             socket.Listen(10);
  24.             while (running)
  25.             {
  26.                 Socket client = socket.Accept();
  27.                 Thread processClient = new Thread(new ParameterizedThreadStart(HandleClient));
  28.  
  29.                 var info = new ClientInfo()
  30.                 {
  31.                     Socket = client,
  32.                     ID = ++clients
  33.                 };
  34.  
  35.                 processClient.Start(info);
  36.             }
  37.         }
  38.  
  39.         public void HandleClient(object client)
  40.         {
  41.             Socket socket = ((ClientInfo)client).Socket;
  42.             int id = ((ClientInfo)client).ID;
  43.             Console.WriteLine("Client connected");
  44.             byte[] buffer = new byte[1024];
  45.             int bytesRead;
  46.             bool talking = true;
  47.             while (talking)
  48.             {
  49.                 bytesRead = 0;
  50.                 try
  51.                 {
  52.                     bytesRead = socket.Receive(buffer);
  53.                 }
  54.                 catch
  55.                 {
  56.                     break;
  57.                 }
  58.  
  59.                 if (bytesRead == 0) {
  60.                     break;
  61.                 }
  62.                 string message = UTF8Encoding.UTF8.GetString(buffer, 0, bytesRead);
  63.                 if (message == "exit") break;
  64.                 Console.WriteLine("Got Message {0} from #{1}", message, id);
  65.             }
  66.             socket.Close();
  67.         }
  68.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement