- Socket
- socket.id
- socket.rooms
- socket.client
- socket.conn
- socket.request
- socket.handshake
- socket.use(fn)
- socket.send([…args][, ack])
- socket.emit(eventName[, …args][, ack])
- socket.on(eventName, callback)
- socket.once(eventName, listener)
- socket.removeListener(eventName, listener)
- socket.removeAllListeners([eventName])
- socket.eventNames()
- socket.onAny(callback)
- socket.prependAny(callback)
- socket.offAny([listener])
- socket.listenersAny()
- socket.join(room)
- socket.leave(room)
- socket.to(room)
- socket.in(room)
- socket.except(rooms)
- socket.compress(value)
- socket.disconnect(close)
- Flag: ‘broadcast’
- Flag: ‘volatile’
- Event: ‘disconnect’
- Event: ‘disconnecting’
Socket
A Socket
is the fundamental class for interacting with browser clients. A Socket
belongs to a certain Namespace
(by default /
) and uses an underlying Client
to communicate.
It should be noted the Socket
doesn’t relate directly to the actual underlying TCP/IP socket
and it is only the name of the class.
Within each Namespace
, you can also define arbitrary channels (called room
) that the Socket
can join and leave. That provides a convenient way to broadcast to a group of Socket
s (see Socket#to
below).
The Socket
class inherits from EventEmitter. The Socket
class overrides the emit
method, and does not modify any other EventEmitter
method. All methods documented here which also appear as EventEmitter
methods (apart from emit
) are implemented by EventEmitter
, and documentation for EventEmitter
applies.
More information can be found here.
socket.id
- (String)
A unique identifier for the session, that comes from the underlying Client
.
socket.rooms
- (Set)
A Set of strings identifying the rooms this client is in.
io.on("connection", (socket) => {
console.log(socket.rooms); // Set { <socket.id> }
socket.join("room1");
console.log(socket.rooms); // Set { <socket.id>, "room1" }
});
socket.client
- (Client)
A reference to the underlying Client
object.
socket.conn
- (engine.Socket)
A reference to the underlying Client
transport connection (engine.io Socket
object). This allows access to the IO transport layer, which still (mostly) abstracts the actual TCP/IP socket.
io.on("connection", (socket) => {
const transport = socket.conn.transport.name; // for example, "polling"
console.log("current transport", transport);
socket.conn.on("upgrade", () => {
const newTransport = socket.conn.transport.name; // for example, "websocket"
console.log("new transport", newTransport);
});
});
socket.request
- (Request)
A getter proxy that returns the reference to the request
that originated the underlying engine.io Client
. Useful for accessing request headers such as Cookie
or User-Agent
.
const cookie = require("cookie");
io.on("connection", (socket) => {
const cookies = cookie.parse(socket.request.headers.cookie || "");
});
socket.handshake
- (Object)
The handshake details:
{
headers: /* the headers sent as part of the handshake */,
time: /* the date of creation (as string) */,
address: /* the ip of the client */,
xdomain: /* whether the connection is cross-domain */,
secure: /* whether the connection is secure */,
issued: /* the date of creation (as unix timestamp) */,
url: /* the request URL string */,
query: /* the query params of the first request */,
auth: /* the authentication payload */
}
Usage:
io.use((socket, next) => {
let handshake = socket.handshake;
// ...
});
io.on("connection", (socket) => {
let handshake = socket.handshake;
// ...
});
socket.use(fn)
History
Version | Changes |
---|---|
v3.0.5 | Restoration of the first implementation. |
v3.0.0 | Removal in favor of socket.onAny() . |
v1.7.2 | The error event is sent directly to the client. |
v1.6.0 | First implementation. |
fn
(Function)
Registers a middleware, which is a function that gets executed for every incoming Packet
and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.
Errors passed to the middleware callback are then emitted as error
events on the server-side:
io.on("connection", (socket) => {
socket.use(([event, ...args], next) => {
if (isUnauthorized(event)) {
return next(new Error("unauthorized event"));
}
// do not forget to call next
next();
});
socket.on("error", (err) => {
if (err && err.message === "unauthorized event") {
socket.disconnect();
}
});
});
socket.send([…args][, ack])
args
ack
(Function)- Returns
Socket
Sends a message
event. See socket.emit(eventName[, …args][, ack]).
socket.emit(eventName[, …args][, ack])
(overrides EventEmitter.emit
)
eventName
(String)args
ack
(Function)- Returns
true
Emits an event to the socket identified by the string name. Any other parameters can be included. All serializable datastructures are supported, including Buffer
.
socket.emit("hello", "world");
socket.emit("with-binary", 1, "2", { 3: "4", 5: Buffer.from([6]) });
The ack
argument is optional and will be called with the client’s answer.
io.on("connection", (socket) => {
socket.emit("an event", { some: "data" });
socket.emit("ferret", "tobi", (data) => {
console.log(data); // data will be "woot"
});
// the client code
// client.on("ferret", (name, fn) => {
// fn("woot");
// });
});
socket.on(eventName, callback)
(inherited from EventEmitter
)
eventName
(String)callback
(Function)- Returns
Socket
Register a new handler for the given event.
socket.on("news", (data) => {
console.log(data);
});
// with several arguments
socket.on("news", (arg1, arg2, arg3) => {
// ...
});
// or with acknowledgement
socket.on("news", (data, callback) => {
callback(0);
});
socket.once(eventName, listener)
socket.removeListener(eventName, listener)
socket.removeAllListeners([eventName])
socket.eventNames()
Inherited from EventEmitter
(along with other methods not mentioned here). See the Node.js documentation for the events module.
socket.onAny(callback)
callback
(Function)
Register a new catch-all listener.
socket.onAny((event, ...args) => {
console.log(`got ${event}`);
});
socket.prependAny(callback)
callback
(Function)
Register a new catch-all listener. The listener is added to the beginning of the listeners array.
socket.prependAny((event, ...args) => {
console.log(`got ${event}`);
});
socket.offAny([listener])
listener
(Function)
Removes the previously registered listener. If no listener is provided, all catch-all listeners are removed.
const myListener = () => { /* ... */ };
socket.onAny(myListener);
// then, later
socket.offAny(myListener);
socket.offAny();
socket.listenersAny()
- Returns
Function[]
Returns the list of registered catch-all listeners.
const listeners = socket.listenersAny();
socket.join(room)
room
(string) | (string[])- Returns
void
|Promise
Adds the socket to the given room
or to the list of rooms.
io.on("connection", (socket) => {
socket.join("room 237");
console.log(socket.rooms); // Set { <socket.id>, "room 237" }
socket.join(["room 237", "room 238"]);
io.to("room 237").emit("a new user has joined the room"); // broadcast to everyone in the room
});
The mechanics of joining rooms are handled by the Adapter
that has been configured (see Server#adapter
above), defaulting to socket.io-adapter.
For your convenience, each socket automatically joins a room identified by its id (see Socket#id
). This makes it easy to broadcast messages to other sockets:
io.on("connection", (socket) => {
socket.on("say to someone", (id, msg) => {
// send a private message to the socket with the given id
socket.to(id).emit("my message", msg);
});
});
socket.leave(room)
room
(String)- Returns
void
|Promise
Removes the socket from the given room
.
io.on("connection", (socket) => {
socket.leave("room 237");
io.to("room 237").emit(`user ${socket.id} has left the room`);
});
Rooms are left automatically upon disconnection.
socket.to(room)
History
Version | Changes |
---|---|
v4.0.0 | Allow to pass an array of rooms. |
v1.0.0 | Initial implementation. |
room
(string) | (string[])- Returns
Socket
for chaining
Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have joined the given room
(the socket itself being excluded).
To emit to multiple rooms, you can call to
several times.
io.on("connection", (socket) => {
// to one room
socket.to("others").emit("an event", { some: "data" });
// to multiple rooms
socket.to("room1").to("room2").emit("hello");
// or with an array
socket.to(["room1", "room2"]).emit("hello");
// a private message to another socket
socket.to(/* another socket id */).emit("hey");
// WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
// named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
});
Note: acknowledgements are not supported when broadcasting.
socket.in(room)
Added in v1.0.0
Synonym of socket.to(room).
socket.except(rooms)
Added in v4.0.0
rooms
(string) | (string[])- Returns
BroadcastOperator
Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have not joined the given rooms
(the socket itself being excluded).
// to all clients except the ones in "room1" and the sender
socket.broadcast.except("room1").emit(/* ... */);
// same as above
socket.except("room1").emit(/* ... */);
// to all clients in "room4" except the ones in "room5" and the sender
socket.to("room4").except("room5").emit(/* ... */);
socket.compress(value)
value
(Boolean) whether to following packet will be compressed- Returns
Socket
for chaining
Sets a modifier for a subsequent event emission that the event data will only be compressed if the value is true
. Defaults to true
when you don’t call the method.
io.on("connection", (socket) => {
socket.compress(false).emit("uncompressed", "that's rough");
});
socket.disconnect(close)
close
(Boolean) whether to close the underlying connection- Returns
Socket
Disconnects this socket. If value of close is true
, closes the underlying connection. Otherwise, it just disconnects the namespace.
io.on("connection", (socket) => {
setTimeout(() => socket.disconnect(true), 5000);
});
Flag: ‘broadcast’
Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
io.on("connection", (socket) => {
socket.broadcast.emit("an event", { some: "data" }); // everyone gets it but the sender
});
Flag: ‘volatile’
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
io.on("connection", (socket) => {
socket.volatile.emit("an event", { some: "data" }); // the client may or may not receive it
});
Event: ‘disconnect’
reason
(String) the reason of the disconnection (either client or server-side)
Fired upon disconnection.
io.on("connection", (socket) => {
socket.on("disconnect", (reason) => {
// ...
});
});
Possible reasons:
Reason | Description |
---|---|
server namespace disconnect | The socket was forcefully disconnected with socket.disconnect() |
client namespace disconnect | The client has manually disconnected the socket using socket.disconnect() |
server shutting down | The server is, well, shutting down |
ping timeout | The client did not send a PONG packet in the pingTimeout delay |
transport close | The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G) |
transport error | The connection has encountered an error |
Event: ‘disconnecting’
reason
(String) the reason of the disconnection (either client or server-side)
Fired when the client is going to be disconnected (but hasn’t left its rooms
yet).
io.on("connection", (socket) => {
socket.on("disconnecting", (reason) => {
console.log(socket.rooms); // Set { ... }
});
});
Note: those events, along with connect
, connect_error
, newListener
and removeListener
, are special events that shouldn’t be used in your application:
// BAD, will throw an error
socket.emit("disconnect");