Advertisement
Guest User

Untitled

a guest
Nov 18th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6.  
  7. namespace MultiServer
  8. {
  9.     class Program
  10.     {
  11.         private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  12.         private static readonly List<Socket> clientSockets = new List<Socket>();
  13.         private const int BUFFER_SIZE = 2048;
  14.         private const int PORT = 100;
  15.         private static readonly byte[] buffer = new byte[BUFFER_SIZE];
  16.  
  17.         static void Main()
  18.         {
  19.             Console.Title = "Server";
  20.             SetupServer();
  21.             Console.ReadLine(); // When we press enter close everything
  22.             CloseAllSockets();
  23.         }
  24.  
  25.         private static void SetupServer()
  26.         {
  27.             Console.WriteLine("Setting up server...");
  28.             serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
  29.             serverSocket.Listen(0);
  30.             serverSocket.BeginAccept(AcceptCallback, null);
  31.             Console.WriteLine("Server setup complete");
  32.         }
  33.  
  34.         /// <summary>
  35.         /// Close all connected client (we do not need to shutdown the server socket as its connections
  36.         /// are already closed with the clients).
  37.         /// </summary>
  38.         private static void CloseAllSockets()
  39.         {
  40.             foreach (Socket socket in clientSockets)
  41.             {
  42.                 socket.Shutdown(SocketShutdown.Both);
  43.                 socket.Close();
  44.             }
  45.  
  46.             serverSocket.Close();
  47.         }
  48.  
  49.         private static void AcceptCallback(IAsyncResult AR)
  50.         {
  51.             Socket socket;
  52.  
  53.             try
  54.             {
  55.                 socket = serverSocket.EndAccept(AR);
  56.             }
  57.             catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
  58.             {
  59.                 return;
  60.             }
  61.  
  62.            clientSockets.Add(socket);
  63.            socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
  64.            Console.WriteLine("Client connected, waiting for request...");
  65.            serverSocket.BeginAccept(AcceptCallback, null);
  66.         }
  67.  
  68.         private static void ReceiveCallback(IAsyncResult AR)
  69.         {
  70.             Socket current = (Socket)AR.AsyncState;
  71.             int received;
  72.  
  73.             try
  74.             {
  75.                 received = current.EndReceive(AR);
  76.             }
  77.             catch (SocketException)
  78.             {
  79.                 Console.WriteLine("Client forcefully disconnected");
  80.                 // Don't shutdown because the socket may be disposed and its disconnected anyway.
  81.                 current.Close();
  82.                 clientSockets.Remove(current);
  83.                 return;
  84.             }
  85.  
  86.             byte[] recBuf = new byte[received];
  87.             Array.Copy(buffer, recBuf, received);
  88.             string text = Encoding.ASCII.GetString(recBuf);
  89.             Console.WriteLine("Received Text: " + text);
  90.  
  91.             if (text.ToLower() == "get time") // Client requested time
  92.             {
  93.                 Console.WriteLine("Text is a get time request");
  94.                 byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
  95.                 current.Send(data);
  96.                 Console.WriteLine("Time sent to client");
  97.             }
  98.             else if (text.ToLower() == "exit") // Client wants to exit gracefully
  99.             {
  100.                 // Always Shutdown before closing
  101.                 current.Shutdown(SocketShutdown.Both);
  102.                 current.Close();
  103.                 clientSockets.Remove(current);
  104.                 Console.WriteLine("Client disconnected");
  105.                 return;
  106.             }
  107.             else
  108.             {
  109.                 Console.WriteLine("Text is an invalid request");
  110.                 byte[] data = Encoding.ASCII.GetBytes("Invalid request");
  111.                 current.Send(data);
  112.                 Console.WriteLine("Warning Sent");
  113.             }
  114.  
  115.             current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
  116.         }
  117.     }
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement