Advertisement
Guest User

Server228

a guest
Dec 12th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.50 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7. using System.Threading;
  8.  
  9. namespace ChatServer
  10. {
  11. //********************************************************
  12.     public class ClientObject
  13.     {
  14.         String userName;
  15.         TcpClient client;
  16.         ServerObject server;                                                        //Объект сервера
  17.  
  18.         protected internal String Id
  19.         {
  20.             get;
  21.             private set;
  22.         }
  23.        
  24.         protected internal NetworkStream Stream
  25.         {
  26.             get;
  27.             private set;
  28.         }
  29.  
  30.         public ClientObject(TcpClient tcpClient, ServerObject serverObject)
  31.         {
  32.             Id = Guid.NewGuid().ToString();
  33.             client = tcpClient;
  34.             server = serverObject;
  35.             serverObject.AddConnection(this);
  36.         }
  37.  
  38.         public void Process()
  39.         {
  40.             try
  41.             {
  42.                 Stream = client.GetStream();
  43.                 String message = GetMessage();                                      //Получаем имя пользователя
  44.                 userName = message;
  45.  
  46.                 message = userName + " вошёл в чат";
  47.                 server.BroadcastMessage(message, this.Id);                          //Посылаем сообщение о входе в чат всем подключенным пользователям
  48.                 Console.WriteLine(message);
  49.  
  50.                 while (true)                                                         //В бесконечном цикле получаем сообщения от клиента
  51.                 {
  52.                     try
  53.                     {
  54.                         message = GetMessage();
  55.                         message = String.Format("{0}: {1}", userName, message);
  56.                         Console.WriteLine(message);
  57.                         server.BroadcastMessage(message, this.Id);
  58.                     }
  59.                     catch
  60.                     {
  61.                         message = String.Format("{0}: покинул чат", userName);
  62.                         Console.WriteLine(message);
  63.                         server.BroadcastMessage(message, this.Id);
  64.                         break;
  65.                     }
  66.                 }
  67.             }
  68.             catch (Exception exception)
  69.             {
  70.                 Console.WriteLine(exception.Message);
  71.             }
  72.             finally
  73.             {
  74.                 server.RemoveConnection(this.Id);
  75.                 Close();
  76.             }
  77.         }
  78.  
  79.         // чтение входящего сообщения и преобразование в строку
  80.         private string GetMessage()
  81.         {
  82.             byte[] data = new byte[64]; // буфер для получаемых данных
  83.             StringBuilder builder = new StringBuilder();
  84.             int bytes = 0;
  85.             do
  86.             {
  87.                 bytes = Stream.Read(data, 0, data.Length);
  88.                 builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
  89.             }
  90.             while (Stream.DataAvailable);
  91.  
  92.             return builder.ToString();
  93.         }
  94.  
  95.         // закрытие подключения
  96.         protected internal void Close()
  97.         {
  98.             if (Stream != null)
  99.                 Stream.Close();
  100.             if (client != null)
  101.                 client.Close();
  102.         }
  103.     }
  104. //***********************************************
  105.  
  106.  
  107. //++++++++++++++++++++++++++++++++++++++++++++++
  108.     public class ServerObject
  109.     {
  110.         static TcpListener tcpListener;                                             //Сервер для прослушивания
  111.         List<ClientObject> clients = new List<ClientObject>();                      //Все подключения
  112.  
  113.         protected internal void AddConnection(ClientObject clientObject)
  114.         {
  115.             clients.Add(clientObject);
  116.         }
  117.  
  118.         protected internal void RemoveConnection(String id)
  119.         {
  120.             //Получаем по id закрытое подключение
  121.             ClientObject client = clients.FirstOrDefault(c => c.Id == id);
  122.            
  123.             //И удаляем его из списка подключений
  124.             if (client != null)
  125.             {
  126.                 clients.Remove(client);
  127.             }
  128.  
  129.         }
  130.  
  131.         //Прослушивание входящих сообщений
  132.         protected internal void Listen()
  133.         {
  134.             try
  135.             {
  136.                 tcpListener = new TcpListener(IPAddress.Any, 8888);
  137.                 tcpListener.Start();
  138.                 Console.WriteLine("Сервер запущен. Ожидание подключений... ");
  139.  
  140.                 while (true)
  141.                 {
  142.                     TcpClient tcpClient = tcpListener.AcceptTcpClient();
  143.  
  144.                     ClientObject clientObject = new ClientObject(tcpClient, this);
  145.                     Thread clientThread = new Thread(new ThreadStart(clientObject.Process));
  146.                     clientThread.Start();
  147.                 }
  148.             }
  149.             catch (Exception exception)
  150.             {
  151.                 Console.WriteLine(exception.Message);
  152.                 Disconnect();                                                                   //Отключение связи
  153.             }
  154.         }
  155.  
  156.  
  157.         //Трансляция сообщения подключённым клиентам
  158.         protected internal void BroadcastMessage(String message, String id)
  159.         {
  160.             byte[] data = Encoding.Unicode.GetBytes(message);
  161.             for (int i = 0; i < clients.Count; i++)
  162.             {
  163.                 if (clients[i].Id != id)                                                        //Если id клиента не равно id отправляющего
  164.                 {
  165.                     clients[i].Stream.Write(data, 0, data.Length);                              //Передача данных
  166.                 }
  167.             }
  168.         }
  169.  
  170.  
  171.         //Отключение всех клиентов
  172.         protected internal void Disconnect()
  173.         {
  174.             tcpListener.Stop();                                                                 //Остановка сервера
  175.  
  176.             for (int i = 0; i < clients.Count; i++)
  177.             {
  178.                 clients[i].Close();                                                             //Отключение клиента
  179.             }
  180.  
  181.             Environment.Exit(0);                                                                //Завершение процесса
  182.         }
  183.  
  184.     }
  185. //+++++++++++++++++++++++++++++++++++++++++++++
  186.  
  187.  
  188.  
  189. //-----------------------------------------------
  190.     class Program
  191.     {
  192.         static ServerObject server; // сервер
  193.         static Thread listenThread; // потока для прослушивания
  194.         static void Main(string[] args)
  195.         {
  196.             try
  197.             {
  198.                 server = new ServerObject();
  199.                 listenThread = new Thread(new ThreadStart(server.Listen));
  200.                 listenThread.Start(); //старт потока
  201.             }
  202.             catch (Exception ex)
  203.             {
  204.                 server.Disconnect();
  205.                 Console.WriteLine(ex.Message);
  206.             }
  207.         }
  208.     }
  209. //----------------------------------------------
  210.  
  211. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement