Permalink
Browse files

Server Send Events example.

  • Loading branch information...
1 parent e377533 commit 446eb27607e214fdd78179cf413ec7e1203338b4 @Bobris committed Mar 6, 2015
Showing with 37 additions and 5 deletions.
  1. +20 −5 SampleOwinApp/Sample.cs
  2. +17 −0 SampleOwinApp/sse.html
@@ -105,31 +105,46 @@ public void Configuration(IAppBuilder app)
return Task.Delay(0);
}));
- app.Run(c =>
+ app.Run(async c =>
{
var path = c.Request.Path.Value;
if (path == "/")
{
c.Response.StatusCode = 200;
c.Response.ContentType = "text/plain";
c.Response.Write("Hello World!");
- return Task.Delay(0);
+ return;
+ }
+ if (path == "/sse")
+ {
+ c.Response.StatusCode = 200;
+ c.Response.ContentType = "text/event-stream";
+ c.Response.Headers.Add("Cache-Control", new[] { "no-cache" });
+ for (int i = 0; i < 10; i++)
+ {
+ await c.Response.WriteAsync("data: " + i.ToString() + "\n\n");
+ await c.Response.Body.FlushAsync();
+ await Task.Delay(500);
+ }
+ await c.Response.WriteAsync("data: Finish!\n\n");
+ return;
}
if (path.Contains(".."))
{
// hackers ..
c.Response.StatusCode = 500;
- return Task.Delay(0);
+ return;
}
var p = Path.Combine(@"..\..\..\SampleOwinApp\", path.Substring(1));
if (File.Exists(p))
{
c.Response.StatusCode = 200;
c.Response.ContentType = p.EndsWith(".js") ? "application/javascript" : "text/html";
- return c.Response.WriteAsync(File.ReadAllBytes(p));
+ await c.Response.WriteAsync(File.ReadAllBytes(p));
+ return;
}
c.Response.StatusCode = 404;
- return Task.Delay(0);
+ return;
});
}
}
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Server Send Events example</title>
+</head>
+<body>
+ <div id="result">
+ </div>
+ <script type="text/javascript">
+ // Start NowinSample and point browser to http://localhost:8888/sse.html
+ var source = new EventSource("sse");
+ source.onmessage = function(event) {
+ document.getElementById("result").innerHTML += event.data + "<br>";
+ };
+ </script>
+</body>
+</html>

0 comments on commit 446eb27

Please sign in to comment.