Socket.io Notes
Socket.io Notes
1. WebSocket Protocol
const express = require('express');
const app = express();
const socketio = require('socket.io');
const expressServer = app.listen(9000);
const io = socketio(expressServer); // The SOCKET SERVER is LISTENING TO THE HTTP SERVER.
Socket.io does not run on the HTTP protocol. It runs on the websocket protocol. The server listens for connections on HTTP and THEN makes a socket. A random TCP port is used on the server.
2. Namespaces
Namespaces: A way to group a bunch of sockets together. Another def: A namespace represents a pool of sockets connected under a given scope idenfieid by the pathname (eg chat)
Namespace Examples
- /admin
- /chat
- / even the index is its own namespace
Example: A workspace within Slack would be considered a namespace.
3. Rooms
Rooms: With each namespace, you can also define arbitrary channels (rooms) that sockets can join and leave.
Example: A channel within Slack would be considered a room.
4. Shorthand Notation
- io.emit is shorthand for io.of('/').emit
- io.on is shorthand for io.of('/').on
- Anytime you see io.Something without of('/'), it is shorthand for /
5. Communicating Across Namespaces
The server can still communicate across namespaces. (server-side). On the client-side, the socket needs to be in THAT namespace in order to get events.
Comments
Post a Comment