This library provides an easy way to use WebSockets in your ASP.NET project. The usage method is similar to ASP.NET MVC controllers, but for WebSocket.
-
Install the NuGet package into your project.
-
Create a new class that inherits from
BaseWebSocketController
.- You can add a RouteAttribute attribute to your class for custom routing.
-
Add methods to your class that will handle WebSocket events.
-
You can add a WebSocketPathAttribute attribute to your method for custom routing.
-
You can add a WebSocketCyclicAttribute attribute to your method to make it cyclic (see example).
-
[Route("/ws")]
public class MyWebSocketController : BaseWebSocketController
{
[WebSocketPath("/")]
public async Task OnOpenAsync()
{
await Client.SendAsync("Hello!");
}
[WebSocketCyclic]
[WebSocketPath("echo")]
public async Task OnMessageAsync(string message)
{
await Client.SendAsync(message);
}
[WebSocketPath("{id}")]
public async Task OnCyclicAsync(string id)
{
await Client.SendAsync("Hello " + id);
await Client.SendAsync("Bye " + id);
}
}