| name | relic-websockets |
| description | Handle WebSocket connections and hijack connections for SSE or custom protocols in Relic. Use when implementing real-time communication, WebSocket endpoints, or server-sent events. |
Relic WebSockets & Connection Hijacking
Relic handlers return a Result, which can be a Response, WebSocketUpgrade, or Hijack. WebSockets and hijacking are built-in -- no extra packages needed.
WebSocket connections
Return a WebSocketUpgrade to upgrade an HTTP connection to a WebSocket:
app.get('/ws', (Request req) {
return WebSocketUpgrade((webSocket) async {
webSocket.sendText('Welcome!');
await for (final event in webSocket.events) {
switch (event) {
case TextDataReceived(text: final message):
webSocket.sendText('Echo: $message');
case CloseReceived():
break;
default:
break;
}
}
});
});
Sending data
webSocket.sendText('Hello!'); // throws on failure
webSocket.trySendText('Hello!'); // silent on failure
Event types
Listen on webSocket.events and pattern-match:
TextDataReceived(text: final message) -- text frame received
CloseReceived() -- connection closed by client
Simple listener pattern
WebSocketUpgrade websocketHandler(Request request) {
return WebSocketUpgrade((ws) async {
ws.events.listen((event) {
log('Received: $event');
});
ws.trySendText('Hello!');
ws.sendText('Hello!');
});
}
Connection hijacking
Return a Hijack to take direct control of the underlying TCP connection. Useful for Server-Sent Events (SSE) or custom protocols: