Websocket EndPoint
An endpoint is the entry point for a WebSocket connection. It is the class responsible for managing the connection between the client and server. An endpoint can host multiple routes and trigger various events. To establish a WebSocket connection, a request must be made using the ws
or wss
protocol to a specified path, which is defined within the endpoint itself.
For example, you can set up multiple connection points on your server, such as /ws_user
and /ws_admin
. Access to each endpoint can be restricted; for instance, only administrators may connect to /ws_admin
. Each of these endpoints can contain routes like:
/ws_user
:GetMyProfile
/ws_admin
:GetAllProfiles
Client-Side Connection with AventusSharp
On the frontend, AventusSharp provides a JavaScript class named Connection
to simplify connection management. However, you may also implement your own class if desired. Messages sent or received over the socket follow a specific format:
export interface SocketMessage { channel: string; data?: any; uid?: string;}
- channel: Identifies the route-specific message so it can be processed appropriately.
- data: Carries the payload, allowing transmission of various data types.
- uid: Tags a message sequence between client and server, enabling responses to be matched with their original requests. For instance, when a user creation message is sent with a unique
uid
, the response will contain the sameuid
, allowing you to display a success message to the creator while notifying other interfaces of the new user without showing a message.
To test your WebSocket endpoint, we provide a connection tool: WebSocket Connection Tool
Creating an Endpoint
To create an endpoint, simply define a class that extends WsEndPoint
and implement the required methods.
Example C# Code: MainEndPoint.cs
using AventusSharp.WebSocket;
namespace Demo.Websocket{ public class MainEndPoint : WsEndPoint { public override string DefinePath() { // Entry path => ws://localhost:5268/my_websocket return "/my_socket"; } }}
Once your endpoint is set up, you can connect using the WebSocket tool. A successful connection will return the message: “Connection successfully established!”
If no endpoint is explicitly defined but routes are created, an endpoint will automatically be created at /ws
.
Additional Endpoint Customization
AventusSharp provides several methods you can override to further customize your endpoint’s behavior:
- Main: Defines if this is the primary endpoint. If the route or event does not specify an endpoint, this endpoint will be used by default. If only one endpoint is created, it will automatically become the main endpoint. If none are defined, an endpoint at
/ws
will be created as the main. - CanOpenConnection: Determines if the connection can be opened.
- OnConnectionOpen: Executes actions when a connection is opened.
- OnConnectionClose: Executes actions when a connection is closed.