📜  EventSource Web API C# (1)

📅  最后修改于: 2023-12-03 15:14:54.868000             🧑  作者: Mango

EventSource Web API C#

Introduction

EventSource is a web API that allows the server to push data updates to the client using the HTTP protocol. It is part of the HTML5 specification and is supported by most modern browsers. In C#, the EventSource API can be accessed using the System.Net.Http namespace.

Usage

To use the EventSource API in C#, you can create a new instance of the EventSource class with the URL of the server as a parameter. You can then subscribe to the MessageReceived event to receive updates from the server.

var eventSource = new EventSource("http://example.com/event-stream");
eventSource.MessageReceived += (sender, e) => {
  // Handle incoming data here
};

The MessageReceived event will be fired whenever the server sends a new update. The EventSource class will automatically handle reconnection attempts and error handling.

Examples
Server-Sent Events

One common usage of the EventSource API is for server-sent events (SSEs). SSEs are a unidirectional communication protocol where the server sends events to the client over a single HTTP connection. SSEs are useful for applications that require real-time updates.

Here's an example of how to use the EventSource API to receive SSEs from the server:

var eventSource = new EventSource("http://example.com/sse-endpoint");
eventSource.MessageReceived += (sender, e) => {
  var data = e.Message.Data;
  // Handle incoming SSE data here
};
Custom Events

With the EventSource API, you can also send custom events from the server to the client. Custom events can have any name and carry any JSON payload. Here's an example of how to send a custom event from the server:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

event: custom-event
data: { "message": "Hello, world!" }

On the client side, you can subscribe to the custom event like this:

var eventSource = new EventSource("http://example.com/custom-endpoint");
eventSource.AddEventListener("custom-event", (sender, e) => {
  var data = e.JsonData;
  // Handle incoming custom event data here
});
Conclusion

The EventSource API is a powerful tool for building real-time web applications. With C#, developers can easily subscribe to incoming data and handle it in real-time.