Websocket route
Introduction
In certain applications, it’s necessary to send real-time events from the server to the client. This is where WebSockets become essential. Unlike traditional HTTP requests, which are initiated by the client, WebSockets allow for a continuous, bidirectional connection between the server and client. This is especially useful in scenarios where real-time updates are critical, such as chat applications, live notifications, financial tickers, and multiplayer games.
Advantages of WebSockets:
- Low Latency: WebSockets maintain a constant connection, reducing the delay in message delivery compared to repeated HTTP requests.
- Efficient Data Transfer: Once the WebSocket connection is established, the overhead for each message is low, making it ideal for applications requiring high-frequency data exchange.
- Persistent Communication: WebSockets enable the server to push data to the client as soon as an event occurs, without the client needing to request it.
Defining Websocket in AventusSharp
AventusSharp’s WebSocket handling is organized into three main components:
WsEndPoint
: The entry point for establishing a WebSocket connection.WsRouter
: Defines WebSocket routes, similar to HTTP routes, for organizing endpoint access points.WsEvent
: Represents events triggered by the server to notify the frontend of specific changes or actions.
When your application starts and you call the register
function on WebSocketMiddleware
, AventusSharp will automatically scan for all IWsEndPoint
and IWsRouter
classes. It will then set up the necessary connections and define routes based on these classes.
Folder Structure Convention:
- WebSocket Endpoints (
WsEndPoint
) should be located in theWebsocket
folder. - Events (
WsEvent
) should be placed in theWebsocket.Events
folder. - Routes (
WsRouter
) should be defined in theWebsocket.Routes
folder.
Example: Defining a Basic Route
The following code demonstrates a simple WebSocket route.
using AventusSharp.WebSocket;
namespace Demo.Websocket.Routes{ public class MainRouter : WsRouter { public string Index() { return "It's working"; } }}
In this example, MainRouter
defines a route that listens for messages on /
, returning "It's working"
when accessed.
With AventusSharp, setting up WebSocket routes and events is straightforward. By following the folder structure convention and using WebSocketMiddleware.register
, your application will automatically configure WebSocket endpoints and routes, enabling real-time communication between your server and clients.