Files
What you'll learn
- Explain what a WebSocket connection adds to HTTP, and what socket.io adds to WebSockets: events, acknowledgements, rooms
- Turn a provider into a gateway with @WebSocketGateway(), on the HTTP server's port, registered in a module's providers
- Handle events with @SubscribeMessage() and read the payload, or one of its properties, with @MessageBody()
- Tell the two ways a handler answers apart: a return value is the acknowledgement, a { event, data } object is an event to the sender, and null or undefined sends nothing at all
Press Run tests to start the app. Its log appears here.Graded endpoints
A socket.io client reaches the gateway on the app's own port, 3000, the same port as the HTTP routes. Nothing is sent on connecting yet
The handler's return value comes back as the acknowledgement, the answer to this one message
@MessageBody('id') picks the id out of the payload
An unknown id is acknowledged with an error object; a handler that returned null or undefined would acknowledge nothing and leave the client waiting
The whole payload with @MessageBody(); the stored cat, with its new id, is the acknowledgement
The gateway and any other provider share the same CatsService, so the cat added over the socket is stored
A { event, data } return value is sent to the sender as that event, not as an acknowledgement
A second client, a second connection to the same gateway
The greeting goes to the client that asked, and Ada, also connected, receives nothing
Run the tests first.