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.


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();
			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);
				Console.WriteLine("Sent: " + stringToEcho);

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: Logo

You are commenting using your 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