windows 10 + raspberry pi 2In this article,  we will see how to create simple Web Server for Raspberry Pi 2 running Windows 10 IoT Core. Because it is a Web Server we don't need UI for this application, we can run it in headless mode.

Open Visual Studio 2015 RC and create Windows IoT Core Background Application solution.

Now we need a web server. This will be simple one. It will always response with "Hello, World!" string.

internal class WebServer
{
    private const uint BufferSize = 8192;

    public void Start()
    {
        StreamSocketListener listener = new StreamSocketListener();

        listener.BindServiceNameAsync("8080");

        listener.ConnectionReceived += async (sender, args) =>
        {
            StringBuilder request = new StringBuilder();
            using (IInputStream input = args.Socket.InputStream)
            {
                byte[] data = new byte[BufferSize];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = BufferSize;
                while (dataRead == BufferSize)
                {
                    await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            using (IOutputStream output = args.Socket.OutputStream)
            {
                using (Stream response = output.AsStreamForWrite())
                {
                    byte[] bodyArray = Encoding.UTF8.GetBytes("<html><body>Hello, World!</body></html>");
                    var bodyStream = new MemoryStream(bodyArray);

                    var header = "HTTP/1.1 200 OK\r\n" + 
                                $"Content-Length: {bodyStream.Length}\r\n" +
                                    "Connection: close\r\n\r\n";

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await response.WriteAsync(headerArray, 0, headerArray.Length);
                    await bodyStream.CopyToAsync(response);
                    await response.FlushAsync();
                }
            }
        };
    }
}

As you can see, we just read request body and send simple HTTP header with HTML content back.

Now we need to start our web server. To do that open StartupTask class:

public void Run(IBackgroundTaskInstance taskInstance)
{
    taskInstance.GetDeferral();
    WebServer server = new WebServer();
    ThreadPool.RunAsync(workItem =>
    {
        server.Start();
    });
}

You should call taskInstance.GetDeferral(); to not let application close immediately after run. To close an application you can call Complete method on BackgroundTaskDeferral instance.

Now you can deploy your application and see how it works. Just type IP and port in browser and you should see "Hello, World!" message.