Server-Sent Events (EventSource)

The Server-Sent Events is a one-way string-based protocol. Data comes from the server, and there are no option to send anything to the server. It’s implemented using the latest draft. While the protocol’s name is Server-Sent Events, the class itself is named EventSource.

When an error occurs, the plugin will try to reconnect once sending the LastEventId to let the server send any buffered message that we should receive.

The EventSource class

The EventSource class is located in the BestHTTP.ServerSentEvents namespace:

using BestHTTP.ServerSentEvents;

var sse = new EventSource(new Uri("http://server.com"));

Properties

These are the publicly exposed properties of the EventSource class:

Events

eventSource.OnOpen += OnEventSourceOpened;

void OnEventSourceOpened(EventSource source)
{
    Debug.log("EventSource Opened!");
}
eventSource.OnMessage += OnEventSourceMessage;

void OnEventSourceMessage(EventSource source, Message msg)
{
    Debug.log("Message: " + msg.Data);
}
eventSource.OnError += OnEventSourceError;

void OnEventSourceError(EventSource source, string error)
{
    Debug.log("Error: " + error);
}
eventSource.OnRetry += OnEventSourceRetry;

bool OnEventSourceRetry(EventSource source)
{
    // disable retry
    return false;
}
eventSource.OnClosed += OnEventSourceClosed;

void OnEventSourceClosed(EventSource source)
{
    Debug.log("EventSource Closed!");
}
eventSource.OnStateChanged += OnEventSourceStateChanged;

void OnEventSourceStateChanged(EventSource source, States oldState, States newState)
{
    Debug.log(string.Format("State Changed {0} => {1}", oldState, newState)));
}
eventSource.OnComment += OnEventSourceComment;

void OnEventSourceComment(EventSource source, string comment)
{
    Debug.log(string.Format("Comment: {0}", comment)));
}

Functions

These are the public functions of the EventSource object.

EventSource eventSource = new EventSource(new Uri("http://server.com"));
eventSource.Open();
eventSource.On("userLogon", OnUserLoggedIn);

void OnUserLoggedIn(EventSource source, Message msg)
{
    Debug.log(msg.Data);
}
eventSource.Off("userLogon");
eventSource.Close();

The Message class

The Message class is a logical unit that contains all the information that a server can send.

Properties