Recently, I am working on a toy project named ReactiveWebServer. It is an event-driven web server built with Rx.
Here’s a simple web server returning “Hello World”.
using (var ws = new WebServer("http://*:8080/")) { const string responseBody = "Hello World"; ws.GET("/") .Subscribe(ctx => ctx.Respond(responseBody)); Console.ReadLine(); }
The code is simple, but there is nothing new compared to other web servers such as NancyFx.
The real power of ReactiveWebServer comes from its ability to handle streaming data. For example, here’s a ServerSentEvent server implementation streaming integers every second.
using (var ws = new WebServer("http://*:8000/")) { ws.GET("/events").Subscribe(ctx => { var obs = Observable.Interval(TimeSpan.FromSeconds(1)) .Select(t => new ServerSentEvent(t.ToString())); ctx.Respond(new ServerSentEventsResponse(obs)); }); Console.ReadLine(); }
Data streaming is made simple and easy. You just need to create an instance of IObservable
<ServerSentEvents
>, wrap it with ServerSentEventsResponse
, and pass the result to ctx.Respond
method.