Overview
Silky provides WebSocket support via the Silky.WebSocket package, enabling server-initiated push messages to connected clients. This is ideal for real-time scenarios such as notifications, chat, live dashboards, and streaming.
Installation
<PackageReference Include="Silky.WebSocket" Version="3.9.2" />
Host Setup
Use ConfigureSilkyWebSocketHostDefaults instead of the standard host builder:
// Program.cs
await Host.CreateDefaultBuilder(args)
.ConfigureSilkyWebSocketHostDefaults<NotificationHostModule>(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.Build()
.RunAsync();
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSilkyHttpCore()
.AddWebSocketCore();
}
public void Configure(IApplicationBuilder app)
{
app.UseWebSockets();
app.UseSilkyWebSocket();
app.UseSilkyRpcProxy();
}
Module
[DependsOn(
typeof(WebSocketModule),
typeof(ZookeeperModule),
typeof(DotNettyTcpModule)
)]
public class NotificationHostModule : SilkyModule { }
WebSocket Service Interface
Define a WebSocket service the same way as a regular application service, but annotate with [WsRoute]:
[WsRoute]
public interface INotificationService
{
Task SendNotificationAsync(NotificationInput input);
Task BroadcastAsync(BroadcastInput input);
}
Implementation
public class NotificationService : INotificationService, IScopedDependency
{
private readonly IWsSessionManager _sessionManager;
public NotificationService(IWsSessionManager sessionManager)
{
_sessionManager = sessionManager;
}
public async Task SendNotificationAsync(NotificationInput input)
{
// Send to a specific user session
var session = _sessionManager.GetByUserId(input.UserId);
if (session != null)
{
await session.SendAsync(input.Message);
}
}
public async Task BroadcastAsync(BroadcastInput input)
{
// Broadcast to all connected clients
foreach (var session in _sessionManager.GetAll())
{
await session.SendAsync(input.Message);
}
}
}
Client Connection
Clients connect to the WebSocket endpoint:
const ws = new WebSocket('ws://gateway-host/ws/notification');
ws.onmessage = (event) => {
const notification = JSON.parse(event.data);
console.log('Received:', notification);
};
ws.onopen = () => {
console.log('WebSocket connected');
};
Configuration
{
"webSocket": {
"keepAliveInterval": 120,
"receiveBufferSize": 4096,
"path": "/ws"
}
}
| Option | Default | Description |
|---|---|---|
keepAliveInterval | 120 | Keep-alive ping interval in seconds |
receiveBufferSize | 4096 | Receive buffer size in bytes |
path | "/ws" | WebSocket connection path prefix |
