Implement WebSockets with Pushpin
mainPushpin supports WebSockets by converting connection activity and messages into HTTP requests sent to your backend. This allows for stateless backend handling.
Key concepts for WebSocket integration:
- Connection Lifecycle: When a new connection arrives, the backend receives a request where
wsContext.isOpening()is true. You must callwsContext.accept()and optionallywsContext.subscribe(channel)to establish the connection. - Message Handling: Messages are received via
wsContext.recv(). Ifrecv()returnsnull, the connection is closed. - Publishing: Use a publisher to broadcast messages to channels using
publisher.publishFormats(channel, format). - Statelessness: The
wsContextonly exists for the duration of the handler invocation. The backend does not need to maintain long-lived socket connections.
const { WebSocketMessageFormat } = require( '@fanoutio/grip' );
app.post('/websocket', async (req, res) => {
const { wsContext } = req.grip;
// If this is a new connection, accept it and subscribe it to a channel
if (wsContext.isOpening()) {
wsContext.accept();
wsContext.subscribe('all');
}
while (wsContext.canRecv()) {
var message = wsContext.recv();
// If return value is null then connection is closed
if (message == null) {
wsContext.close();
break;
}
// broadcast the message to everyone connected
await publisher.publishFormats('all', WebSocketMessageFormat(message));
}
res.end();
});