deleriumbg

Simple Web Server

Nov 26th, 2018
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Simple_Web_Server
  8. {
  9.     class Program
  10.     {
  11.         private const string LocalhostIpAddress = "127.0.0.1";
  12.         private const int Port = 1300;
  13.         private const int BufferSize = 1024;
  14.  
  15.         static void Main(string[] args)
  16.         {
  17.             IPAddress address = IPAddress.Parse(LocalhostIpAddress);
  18.             TcpListener listener = new TcpListener(address, Port);
  19.             listener.Start();
  20.  
  21.             Console.WriteLine("Server started.");
  22.             Console.WriteLine($"Listening to TCP clients at {LocalhostIpAddress}:{Port}");
  23.  
  24.             Task task = Task.Run(() => ConnectWithTcpClient(listener));
  25.             task.Wait();
  26.         }
  27.  
  28.         private static async Task ConnectWithTcpClient(TcpListener listener)
  29.         {
  30.             while (true)
  31.             {
  32.                 Console.WriteLine("Waiting for client...");
  33.                 var client = await listener.AcceptTcpClientAsync();
  34.                 Console.WriteLine("Client connected.");
  35.  
  36.                 byte[] buffer = new byte[BufferSize];
  37.                 client.GetStream().Read(buffer, 0, buffer.Length);
  38.  
  39.                 var message = Encoding.ASCII.GetString(buffer);
  40.                 Console.WriteLine(message);
  41.  
  42.                 byte[] data = Encoding.ASCII.GetBytes("Hello from server!");
  43.                 client.GetStream().Write(data, 0, data.Length);
  44.  
  45.                 Console.WriteLine("Closing connection.");
  46.                 client.GetStream().Dispose();
  47.             }
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment