Websocket Events
In AventusSharp, an event is a class that enables sending messages from the server to one or more clients. Events are created by defining a class that inherits from WsEvent<T>
, where T
represents the message body. By convention, the body is defined as an inner class within the event class.
using AventusSharp.WebSocket.Event;
namespace Demo.Websocket{ public class HelloEvent : WsEvent<HelloEvent.Body> { protected override Task<Body> Prepare() { return Task.FromResult(new Body() { message = "Hello world!" }); }
public class Body { public string message; } }}
Emitting an Event
To send a message from the server to the client, create an event instance and use the EmitTo
method. You can either emit the event to a specific connection or broadcast it to all open connections on a particular endpoint.
using AventusSharp.WebSocket;
namespace Demo.Websocket{ public class MainEndPoint : WsEndPoint { public override string DefinePath() { return "/ws"; }
protected override Task OnConnectionOpen(WebSocketConnection connection) { // Emit only to the current connection new HelloEvent().EmitTo(connection);
// Broadcast to all open connections on MainEndPoint // new HelloEvent().EmitTo<MainEndPoint>();
return base.OnConnectionOpen(connection); } }}
Receiving the Event
When a client connects, it will receive a message formatted as follows:
{ "channel": "Demo.Websocket.HelloEvent", "data": { "$type": "Demo.Websocket.HelloEvent+Body, Demo", "message": "Hello world!" }}
As shown, the channel
is set to the fully qualified name of the event class by default.
Customizing the Channel Name
You can override the default channel name by applying the Path
attribute to the event class.
using AventusSharp.WebSocket.Event;using Path = AventusSharp.WebSocket.Attributes.Path;
namespace Demo.Websocket{ [Path("/HelloEvent")] public class HelloEvent : WsEvent<HelloEvent.Body> { // Implementation remains the same }}
With this approach, the channel
value will be updated to reflect the custom path specified in the Path
attribute.