An HTTP Echo Server in C# Using HttpListener

The C# code below implements a rudimentary HTTP server that simply echoes whatever is sent to it back to the client.

HttpEchoServer.png


using System;
using System.Net;
using System.IO;
using System.Text;

namespace HttpEchoServer
{
	public class HttpEchoServer
	{
		public static void Main()
		{
			string addressToListenOn = "http://localhost:1234/";
			Console.WriteLine("Starting echo server on " + addressToListenOn + "...");
			HttpListener listener = new HttpListener();
			listener.Prefixes.Add(addressToListenOn);
			listener.Start();
			while (true)
			{
				HttpListenerContext context = listener.GetContext();
				HttpListenerRequest request = context.Request;
				string stringToEcho = new StreamReader(request.InputStream).ReadToEnd();
				Console.WriteLine("Received: " + stringToEcho);
				HttpListenerResponse response = context.Response;
				byte[] responseBuffer = Encoding.UTF8.GetBytes(stringToEcho);
				response.ContentLength64 = responseBuffer.Length;
				Stream output = response.OutputStream;
				output.Write(responseBuffer, 0, responseBuffer.Length);
				output.Close();
				Console.WriteLine("Sent: " + stringToEcho);
			}
		}
	}
}

Advertisements
This entry was posted in Uncategorized and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s