Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Net.Sockets;
  7. using System.IO;
  8.  
  9. namespace MultiServeris
  10. {
  11.     class Multiserveris
  12.     {
  13.        
  14.         static void Main(string[] args)
  15.         {
  16.             TcpListener ServerSocket = new TcpListener(1000);         // listens on port number 1000
  17.             ServerSocket.Start();                                     // start listener
  18.             List<TcpClient> clients = new List<TcpClient>();
  19.             Console.WriteLine("Serveris paleistas. Laukiama klientu...");
  20.             while (true)
  21.             {
  22.                 // creates clients list
  23.                 TcpClient clientSocket = ServerSocket.AcceptTcpClient();        // wait for client to make request
  24.                 clients.Add(clientSocket); // Adds client to list
  25.  
  26.                 handleClient client = new handleClient();                       // handle each client
  27.                 client.startClient(clientSocket);
  28.  
  29.  
  30.             }
  31.  
  32.  
  33.         }
  34.     }
  35.  
  36.     public class handleClient
  37.     {
  38.         TcpClient clientSocket;                                   // client socket
  39.         List<TcpClient> clients;
  40.         public void startClient(TcpClient inClientSocket)
  41.         {
  42.             this.clientSocket = inClientSocket;
  43.             Thread ctThread = new Thread(Chat);                    // start thread for each client
  44.             ctThread.Start();
  45.         }
  46.  
  47.         private void Chat()
  48.         {
  49.             byte[] msg = new byte[1024];
  50.             while (true)
  51.             {
  52.                 NetworkStream ns = clientSocket.GetStream();
  53.  
  54.                 ns.Read(msg, 0, 100);
  55.  
  56.                 ns.Flush();
  57.                 Broadcast(msg);
  58.             }
  59.         }
  60.         private void Broadcast(byte[] msg)
  61.         {
  62.             foreach (var client in clients)
  63.             {
  64.                 NetworkStream ns = client.GetStream();
  65.                 ns.Write(msg, 0, 100);
  66.                 ns.Flush();
  67.             }
  68.         }
  69.  
  70.  
  71.  
  72.  
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement