In my Windows Runtime app, I set up a listener like this:
StreamSocketListener streamSocketListener = new StreamSocketListener();
streamSocketListener.ConnectionReceived += streamSocketListener_ConnectionReceived;
await streamSocketListener.BindEndpointAsync(hostName, port);
But the browser keeps loading and fails at the end.
I tested a file's stream and it returned unreadable characters.
How to send a string using StreamSocket?
The correct answer to your specific question is that your connection event handler should look something like this:
private async void streamSocketListener_ConnectionReceived(
StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataWriter writer = new DataWriter(args.Socket.OutputStream);
writer.WriteString(responseHtml);
await writer.StoreAsync();
await writer.FlushAsync();
}
Where responseHtml
is the HTML string you want to send (e.g. the HTTP response, with the Content-Length
filled in of course).
Alternatively, use System.Text.Encoding
to encode the string manually yourself, and then send the bytes using the DataWriter.WriteBytes()
method instead.
Note of course that there's a lot more to writing an HTTP server for WinRT than that. You should actually be using the connection event to create some persistent client data structure, where you keep whatever object(s) you'll be using for the I/O and of course any other client-related state. After sending any response, you'll also initiate whatever mechanism you intend to use to receive more data.
Unfortunately, AFAIK the WinRT API, unlike the desktop .NET API, does not provide an HTTP server implementation, e.g. like System.Net.HttpListener
. But if you know how to manage the HTTP protocol yourself, you should be fine once you nail down the other specifics of dealing with the I/O.