Advertisement
Guest User

TCP SERVER

a guest
Jun 25th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.75 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Engine.Advanced;
  11. using Engine.Base;
  12.  
  13. namespace Engine
  14. {
  15.     namespace Advanced
  16.     {
  17.         /// <summary>
  18.         /// This namespace contains classes that allow TCP connections.
  19.         /// </summary>
  20.         namespace TCP
  21.         {
  22.             /// <summary>
  23.             /// Basic TCP "Server" class.
  24.             /// </summary>
  25.             public class AsyncServerSocket
  26.             {
  27.                 private TcpListener _server;
  28.                 private bool _isRunning;
  29.                 private bool _isFull;
  30.                 private bool _isWarning;
  31.                 private int MAX_CONNECTIONS;
  32.                 public int CURRENT_CONNECTIONS = 0;
  33.                 private DateTime CREATION_TIME;
  34.                 public List<Client> Clients;
  35.  
  36.                 public delegate void ClientConnected(Client sender);
  37.                 public event ClientConnected OnClientConnected;
  38.  
  39.                 public void SetMAX_CONNECTIONS(int value)
  40.                 {
  41.                     MAX_CONNECTIONS = value;
  42.                 }
  43.  
  44.                 public AsyncServerSocket(int port)
  45.                 {
  46.                     _server = new TcpListener(IPAddress.Any, port);
  47.                     _server.Start();
  48.                     MAX_CONNECTIONS = 10;
  49.                     _isRunning = true;
  50.                     _isFull = false;
  51.                     _isWarning = false;
  52.                     Clients = new List<Client>();
  53.  
  54.                 }
  55.  
  56.                 public void Start()
  57.                 {
  58.                     CREATION_TIME = DateTime.Now;
  59.                     while (_isRunning)
  60.                     {
  61.  
  62.                         // wait for client connection
  63.                         TcpClient connection = _server.AcceptTcpClient();
  64.                         CURRENT_CONNECTIONS++;
  65.                         Client newClient = new Client(CURRENT_CONNECTIONS, connection);
  66.                         OnClientConnected(newClient);
  67.                         CheckServerSatus();
  68.                         SendServerStatus(newClient);
  69.  
  70.                         // client found.
  71.  
  72.                         if (_isFull)
  73.                         {
  74.                             ServerFull(newClient);
  75.                             newClient = null;
  76.                         }
  77.                         else
  78.                         {
  79.                             Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
  80.                             t.Start(newClient);
  81.                         }
  82.                     }
  83.                 }
  84.  
  85.                 private void HandleClient(object c)
  86.                 {
  87.                     Client client = (Client) c;
  88.                     client.OnConnectionClosed += Client_OnConnectionClosed;
  89.                     Clients.Add(client);
  90.                     client.Start();
  91.                 }
  92.  
  93.                 private void Client_OnConnectionClosed(Client sender)
  94.                 {
  95.                     CommandLine.ErrorMsg("Client " + sender.ID + " Disconected.");
  96.                 }
  97.  
  98.                 private void CheckServerSatus()
  99.                 {
  100.                     _isRunning = _server.Server.IsBound;
  101.                     _isFull = CURRENT_CONNECTIONS > MAX_CONNECTIONS;
  102.                     _isWarning = General.getPercent(MAX_CONNECTIONS, CURRENT_CONNECTIONS) >= 70 && CURRENT_CONNECTIONS <= MAX_CONNECTIONS;
  103.                 }
  104.  
  105.                 private void SendServerStatus(Client newClient)
  106.                 {
  107.                     byte status = 0;
  108.  
  109.                     bool[] stats = { _isRunning, _isWarning, _isFull };
  110.  
  111.                     // This assumes the array never contains more than 8 elements!
  112.                     int index = 0;
  113.  
  114.                     // Loop through the array
  115.                     foreach (bool b in stats)
  116.                     {
  117.                         // if the element is 'true' set the bit at that position
  118.                         if (b)
  119.                             status |= (byte)(1 << (index));
  120.  
  121.                         index++;
  122.                     }
  123.  
  124.                     newClient.SendMessage(status.ToString());
  125.                 }
  126.  
  127.  
  128.  
  129.  
  130.                 private void ServerFull(Client obj)
  131.                 {
  132.                     obj._client.Close();
  133.                     CURRENT_CONNECTIONS--;
  134.                 }
  135.  
  136.                 public void Stop()
  137.                 {
  138.                     _isRunning = false;
  139.                 }
  140.  
  141.                 public ServerStatus GetStatus()
  142.                 {
  143.                     return new ServerStatus(this);
  144.                 }
  145.  
  146.                 #region CHILD CLASSES
  147.                 public class ServerStatus
  148.                 {
  149.                     public bool Running;
  150.                     public bool Full;
  151.                     public bool Warning;
  152.                     public int MAX_CONNECTIONS;
  153.                     public int CURRENT_CONNECTIONS;
  154.                     public double USAGE_PERCENT;
  155.                     public TimeSpan TimeRunning;
  156.  
  157.                     public ServerStatus(AsyncServerSocket server)
  158.                     {
  159.                         Running = server._isRunning;
  160.                         Full = server._isFull;
  161.                         Warning = server._isWarning;
  162.                         MAX_CONNECTIONS = server.MAX_CONNECTIONS;
  163.                         CURRENT_CONNECTIONS = server.CURRENT_CONNECTIONS;
  164.                         USAGE_PERCENT = General.getPercent(MAX_CONNECTIONS, CURRENT_CONNECTIONS);
  165.                         TimeRunning = DateTime.Now - server.CREATION_TIME;
  166.                     }
  167.                 }
  168.  
  169.                 public class Client
  170.                 {
  171.                     public int ID;
  172.                     public TcpClient _client;
  173.  
  174.                     public delegate void MessageRecieved(Client sender, string message);
  175.                     public event MessageRecieved OnMessageRecieved;
  176.  
  177.                     public delegate void ConnectionClosed(Client sender);
  178.                     public event ConnectionClosed OnConnectionClosed;
  179.  
  180.                     public Client(int iD, TcpClient client)
  181.                     {
  182.                         ID = iD;
  183.                         _client = client;
  184.                     }
  185.  
  186.                     public void Start()
  187.                     {
  188.                         StreamReader sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
  189.                         // you could use the NetworkStream to read and write,
  190.                         // but there is no forcing flush, even when requested
  191.  
  192.                         do
  193.                         {
  194.                             try
  195.                             {
  196.                                 // reads from stream
  197.                                 string sData = sReader.ReadLine();
  198.                                 // shows content on the console.
  199.                                 OnMessageRecieved(this, sData);
  200.                             }
  201.                             catch (Exception ex)
  202.                             {
  203.                                 //Console.WriteLine(ex.Message);
  204.                             }
  205.  
  206.                         } while (_client.Connected);
  207.                         OnConnectionClosed(this);
  208.                     }
  209.  
  210.                     public void SendMessage(string message)
  211.                     {
  212.                         StreamWriter sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);
  213.                         sWriter.WriteLine(message);
  214.                         sWriter.Flush();
  215.                     }
  216.                 }
  217.                 #endregion
  218.             }
  219.         }
  220.     }
  221. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement