Showing posts with label EventSource. Show all posts
Showing posts with label EventSource. Show all posts

Saturday, 6 July 2013

C# client for Server Side Events (EventSource)

Examples of one way streaming from server to client can be found on the web but it’s pretty much always JavaScript clients.  Here is a working example using the .NET stack, with WebAPI as the server and a C# console application as the client.

Download and run this WebAPI chat application which emits Server Side Events:

https://github.com/filipw/html5-push-asp.net-web-api/

I then open Visual Studio running as admin, update the code to use IIS with my machine name (Zeus) and a virtual directory, clicking the create virtual directory button, so I can track requests using Fiddler:

image

Then update the JavaScript within the app to use the same path:

image

The create a Console application, using NUGET add Json.NET and paste this code in:

using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
new WebClientWrapper();
Console.ReadKey();
}
}

public class WebClientWrapper
{
WebClient wc { get; set; }

public WebClientWrapper()
{
InitialiseWebClient();
}

// When SSE (Server side event) occurs this fires
private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs args)
{
using (var streamReader = new StreamReader(args.Result, Encoding.UTF8))
{
var cometPayload = streamReader.ReadLine();
var jsonPayload = cometPayload.Substring(5);
var message = JsonConvert.DeserializeObject<Message>(jsonPayload);
Console.WriteLine("Message received: {0} {1} {2}", message.dt, message.username, message.text);
InitialiseWebClient();
}
}

private void InitialiseWebClient()
{
wc = new WebClient();
wc.OpenReadAsync(new Uri("http://zeus/chatapp/api/chat/"));
wc.OpenReadCompleted += OnOpenReadCompleted;
}
}

public class Message
{
public string username { get; set; }
public string text { get; set; }
public string dt { get; set; }
}
}


You’ll need to update the code for your machine name.


Now run Fiddler, the WebAPI project and the console app and add a message in the chat window:


image


In Fiddler, select the request your console just made and select Raw, you’ll see nothing.  Now right click and select COMETPeek and you’ll see the payload that was streamed.


image

Wednesday, 19 October 2011

HTML5 Server Side Events

Overview

Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.

It is commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.

This means the client can receive a one way fire hose of data from the server for such scenarios as new FX rates, stock prices, new message received, etc.

But I thought we had Web Sockets for this?  Yes, HTML5 does provide Web Sockets but that is for full duplex (bi-directional) data transfer whereas SSE can be used for one way communication from server to client.

image

In our simple example

  • The client automatically registers for Server Sent Events, setting Id to the current time (in JavaScript)
  • Every 5 seconds the server pushes event data to the client
  • The data, made up of three parts Id, Detail and Timestamp is displayed on the page.
  • A message counter is incremented for each message received.
  • The Server terminates the connection after 10 seconds (after 3 messages)
  • The cycle starts with the client registering for events.

 

Points of Interest

Notice how in the screenshot only two HTTP GETs were sent from the client to the server data URI (stream.php), one for each connection that was made.  The connection is kept open whilst the 3 events/messages are pushed the client.

Data format

In our example we are using JSON data format within the Event-Stream data format. We also need to set the Content Type of the event to “text/event-stream”.

To be able to set the HTTP header content type, we’ll be using a simple php script:

HTML Source

You can view the page online:  http://stevenhollidge.com/html5demos/server-sent-events/