Archive

Posts Tagged ‘web server’

MonoTouch: Simple Web Server

August 18, 2010 Leave a comment

A web server can be a very flexible solution to transferring data from your application. MonoTouch makes it extremely easy to add a web server to your iPhone/iPad application by using the HttpListener class. You can actually implement one with just two methods.

Now this is a very simple example that will just serve up some HTML but you can start from it and extend it to whatever your needs may be. Download the solution file here.

You’ll need to declare two member variables:

private HttpListener listener;
private bool listenerRunning = false;

I used a button click event to both start and stop the server:

partial void startOrStopServer (UIButton sender)
{
	if (!listenerRunning) {
		listener = new HttpListener();
		//Add generic prefix using port 8080
		listener.Prefixes.Add("http://*:8080/");
		
		//Start the server
		listener.Start();
		txtInfo.Text += "Server Started\n";
		btnStart.SetTitle("Stop Server", UIControlState.Normal);
	
		//Begin listening for requests asynchronously
		listener.BeginGetContext(new AsyncCallback(HandleRequest), listener);
	} else {
		//Close the server
		listener.Close();
		listener = null;
		txtInfo.Text += "Server Stoped\n";
		btnStart.SetTitle("Start Server", UIControlState.Normal);
	}
	
	listenerRunning = !listenerRunning;
} 

Request handler method:

private void HandleRequest(IAsyncResult result) {
	if (!listenerRunning) return;
	
	//Get the listener context
	HttpListenerContext context = listener.EndGetContext(result);
	//Start listening for the next request
	listener.BeginGetContext(new AsyncCallback(HandleRequest), listener);
	
	//Update status on the UI thread
	InvokeOnMainThread( delegate {
		txtInfo.Text += "Received request from: " + context.Request.UserHostAddress + "\n";
	});
	
	//Here you can create any response that you want. You can serve text or a file or whatever else you need.
	string response = "<html><head><title>Sample Response</title></head><body>Response from mtouchwebserver.</body></html>";
	byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
	
	//Set some response information
	context.Response.ContentType = "text/html";
	context.Response.StatusCode = (int)HttpStatusCode.OK;
	context.Response.ContentLength64 = responseBytes.Length;
	
	//Write the response.
	context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
	context.Response.OutputStream.Close();
}

You can run the example solution in the iPhone simulator, start the server, then open a browser and go to http://localhost:8080 to see the results.

Categories: C#, iPhone, MonoTouch Tags: , , ,
Follow

Get every new post delivered to your Inbox.