Skip to content

Getting Started

EventSource 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 specification.

Usage Guide for EventSource

The EventSource class offers a simple way to establish and manage communication based on the Server-Sent Events protocol.

Initializing EventSource

Connect to a Server-Sent Events endpoint:

using Best.ServerSentEvents;
var sse = new EventSource(new Uri("https://server/sse"));

Starting and Stopping

Starting the connection
sse.Open();
Stopping the connection
sse.Close();

Listening to Basic Events

Connection Establishment
1
2
3
4
5
6
sse.OnOpen += OnEventSourceOpened;

void OnEventSourceOpened(EventSource source)
{
    Debug.log("Connection established!");
}
Receiving Messages
1
2
3
4
5
6
sse.OnMessage += OnEventSourceMessage;

void OnEventSourceMessage(EventSource source, Message msg)
{
    Debug.log($"Received message: {msg.Data}");
}

Subscribing to Custom Events

Listen to specific events dispatched by the server
1
2
3
4
5
6
sse.On("userLogon", OnUserLoggedIn);

void OnUserLoggedIn(EventSource source, Message msg)
{
    Debug.log($"User logged in: {msg.Data}");
}

Handling Errors and Reconnections

Error Handling
1
2
3
4
5
6
sse.OnError += OnEventSourceError;

void OnEventSourceError(EventSource source, string error)
{
    Debug.log($"Error encountered: {error}");
}
Managing Reconnections
1
2
3
4
5
6
7
sse.OnRetry += OnEventSourceRetry;

bool OnEventSourceRetry(EventSource source)
{
    Debug.log("Attempting reconnection...");
    return true;  // Allow reconnection. Returning false will prevent retry.
}

Unsubscribing from Events

To stop listening to a specific event
sse.Off("userLogon");

Comments