- Class: Server
- new Server(httpServer[, options])
- new Server(port[, options])
- new Server(options)
- server.sockets
- server.serveClient([value])
- server.path([value])
- server.adapter([value])
- server.origins([value])
- server.origins(fn)
- server.attach(httpServer[, options])
- server.attach(port[, options])
- server.listen(httpServer[, options])
- server.listen(port[, options])
- server.bind(engine)
- server.onconnection(socket)
- server.of(nsp)
- server.close([callback])
- Class: Namespace
- Class: Socket
- socket.id
- socket.rooms
- socket.client
- socket.conn
- socket.request
- socket.use(fn)
- socket.send([...args][, ack])
- socket.emit(eventName[, ...args][, ack])
- socket.on(eventName, callback)
- socket.join(room[, callback])
- socket.leave(room[, callback])
- socket.to(room)
- socket.in(room)
- socket.compress(value)
- socket.disconnect(close)
- Flag: 'broadcast'
- Flag: 'volatile'
- Event: 'disconnect'
- Event: 'error'
- Event: 'disconnecting'
- Class: Client
Exposed by require('socket.io')
.
httpServer
(http.Server) the server to bind to.options
(Object)path
(String): name of the path to capture (/socket.io
)serveClient
(Boolean): whether to serve the client files (true
)adapter
(Adapter): the adapter to use. Defaults to an instance of theAdapter
that ships with socket.io which is memory based. See socket.io-adapterorigins
(String): the allowed origins (*
)allowRequest
(Function): A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information:fn(err, success)
, wheresuccess
is a boolean value where false means that the request is rejected, and err is an error code.
Works with and without new
:
var io = require('socket.io')();
// or
var Server = require('socket.io');
var io = new Server();
The same options passed to socket.io are always passed to the engine.io
Server
that gets created. See engine.io options as reference.
Among those options:
pingTimeout
(Number): how many ms without a pong packet to consider the connection closed (60000
)pingInterval
(Number): how many ms before sending a new ping packet (25000
).
Those two parameters will impact the delay before a client knows the server is not available anymore. For example, if the underlying TCP connection is not closed properly due to a network issue, a client may have to wait up to pingTimeout + pingInterval
ms before getting a disconnect
event.
transports
(Array): transports to allow connections to (['polling', 'websocket']
).
Note: The order is important. By default, a long-polling connection is established first, and then upgraded to WebSocket if possible. Using ['websocket']
means there will be no fallback if a WebSocket connection cannot be opened.
port
(Number) a port to listen to (a newhttp.Server
will be created)options
(Object)
See above for available options.
options
(Object)
See above for available options.
- (Namespace)
The default (/
) namespace.
#### server.serveClient([value])
value
(Boolean)- Returns
Server|Boolean
If value
is true
the attached server (see Server#attach
) will serve the client files. Defaults to true
. This method has no effect after attach
is called. If no arguments are supplied this method returns the current value.
// pass a server and the `serveClient` option
var io = require('socket.io')(http, { serveClient: false });
// or pass no server and then you can call the method
var io = require('socket.io')();
io.serveClient(false);
io.attach(http);
#### server.path([value])
value
(String)- Returns
Server|String
Sets the path value
under which engine.io
and the static files will be served. Defaults to /socket.io
. If no arguments are supplied this method returns the current value.
#### server.adapter([value])
value
(Adapter)- Returns
Server|Adapter
Sets the adapter value
. Defaults to an instance of the Adapter
that ships with socket.io which is memory based. See socket.io-adapter. If no arguments are supplied this method returns the current value.
value
(String)- Returns
Server|String
Sets the allowed origins value
. Defaults to any origins being allowed. If no arguments are supplied this method returns the current value.
fn
(Function)- Returns
Server
Provides a function taking two arguments origin:String
and callback(error, success)
, where success
is a boolean value indicating whether origin is allowed or not.
Potential drawbacks:
- in some situations, when it is not possible to determine
origin
it may have value of*
- As this function will be executed for every request, it is advised to make this function work as fast as possible
- If
socket.io
is used together withExpress
, the CORS headers will be affected only forsocket.io
requests. For Express can use cors.
httpServer
(http.Server) the server to attach tooptions
(Object)
Attaches the Server
to an engine.io instance on httpServer
with the supplied options
(optionally).
port
(Number) the port to listen onoptions
(Object)
Attaches the Server
to an engine.io instance on a new http.Server with the supplied options
(optionally).
#### server.listen(httpServer[, options])
Synonym of server.attach(httpServer[, options]).
Synonym of server.attach(port[, options]).
#### server.bind(engine)
engine
(engine.Server)- Returns
Server
Advanced use only. Binds the server to a specific engine.io Server
(or compatible API) instance.
socket
(engine.Socket)- Returns
Server
Advanced use only. Creates a new socket.io
client from the incoming engine.io (or compatible API) Socket
.
nsp
(String)- Returns
Namespace
Initializes and retrieves the given Namespace
by its pathname identifier nsp
. If the namespace was already initialized it returns it immediately.
callback
(Function)
Closes the socket.io server. The callback
argument is optional and will be called when all connections are closed.
var Server = require('socket.io');
var PORT = 3030;
var server = require('http').Server();
var io = Server(PORT);
io.close(); // Close current server
server.listen(PORT); // PORT is free to use
io = Server(server);
Represents a pool of sockets connected under a given scope identified
by a pathname (eg: /chat
).
By default the client always connects to /
.
- (String)
The namespace identifier property.
- (Object)
The hash of Socket
objects that are connected to this namespace, indexed by id
.
eventName
(String)args
Emits an event to all connected clients. The following two are equivalent:
var io = require('socket.io')();
io.emit('an event sent to all connected clients'); // main namespace
var chat = io.of('/chat');
chat.emit('an event sent to all connected clients in chat namespace');
callback
(Function)
Gets a list of client IDs connected to this namespace (across all nodes if applicable).
var io = require('socket.io')();
io.of('/chat').clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
An example to get all clients in namespace's room:
var io = require('socket.io')();
io.of('/chat').in('general').clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
As with broadcasting, the default is all clients from the default namespace ('/'):
var io = require('socket.io')();
io.clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
fn
(Function)
Registers a middleware, which is a function that gets executed for every incoming Socket
, and receives as parameters the socket and a function to optionally defer execution to the next registered middleware.
Errors passed to middleware callbacks are sent as special error
packets to clients.
var io = require('socket.io')();
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
error
(Object) error object
Fired upon a reconnection attempt error.
Synonym of Event: 'connect'.
Sets a modifier for a subsequent event emission that the event data may be lost if the clients are 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.volatile.emit('an event', { some: 'data' }); // the clients may or may not receive it
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node (when the Redis adapter is used).
io.local.emit('an event', { some: 'data' });
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).
- (String)
A unique identifier for the session, that comes from the underlying Client
.
- (Object)
A hash of strings identifying the rooms this client is in, indexed by room name.
- (Client)
A reference to the underlying Client
object.
- (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.
- (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
.
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 middleware callbacks are sent as special error
packets to clients.
var io = require('socket.io')();
io.on('connection', function(socket){
socket.use(function(packet, next){
if (packet.doge === true) return next();
next(new Error('Not a doge error'));
});
});
args
ack
(Function)- Returns
Socket
Sends a message
event. See socket.emit(eventName[, ...args][, ack]).
eventName
(String)args
ack
(Function)- Returns
Socket
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: new Buffer(6) });
The ack
argument is optional and will be called with the server answer.
var io = require('socket.io')();
io.on('connection', function(client){
client.emit('an event', { some: 'data' });
client.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
// the client code
// client.on('ferret', function (name, fn) {
// fn('woot');
// });
});
eventName
(String)callback
(Function)- Returns
Socket
Register a new handler for the given event.
socket.on('news', function (data) {
console.log(data);
});
room
(String)callback
(Function)- Returns
Socket
for chaining
Adds the client to the room
, and fires optionally a callback with err
signature (if any).
io.on('connection', function(socket){
socket.join('room 237', function(){
console.log(socket.rooms); // [ <socket.id>, 'room 237' ]
io.to('room 237', '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 this id (see Socket#id
). This makes it easy to broadcast messages to other sockets:
io.on('connection', function(client){
client.on('say to someone', function(id, msg){
// send a private message to the socket with the given id
client.broadcast.to(id).emit('my message', msg);
});
});
room
(String)callback
(Function)- Returns
Socket
for chaining
Removes the client from room
, and fires optionally a callback with err
signature (if any).
Rooms are left automatically upon disconnection.
room
(String)- Returns
Socket
for chaining
Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room
.
To emit to multiple rooms, you can call to
several times.
var io = require('socket.io')();
io.on('connection', function(client){
// to one room
client.to('others').emit('an event', { some: 'data' });
// to multiple rooms
client.to('room1').to('room2').emit('hello');
});
Synonym of socket.to(room).
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.
close
(Boolean) whether to close the underlying connection- Returns
Socket
Disconnects this client. If value of close is true
, closes the underlying connection. Otherwise, it just disconnects the namespace.
Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
var io = require('socket.io')();
io.on('connection', function(socket){
socket.broadcast.emit('an event', { some: 'data' }); // everyone gets it but the sender
});
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).
var io = require('socket.io')();
io.on('connection', function(socket){
socket.volatile.emit('an event', { some: 'data' }); // the client may or may not receive it
});
reason
(String) the reason of the disconnection (either client or server-side)
Fired upon disconnection.
error
(Object) error object
Fired when an error occurs.
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).
These are reserved events (along with connect
, newListener
and removeListener
) which cannot be used as event names.
The Client
class represents an incoming transport (engine.io) connection. A Client
can be associated with many multiplexed Socket
s that belong to different Namespace
s.
- (engine.Socket)
A reference to the underlying engine.io
Socket
connection.
- (Request)
A getter proxy that returns the reference to the request
that originated the engine.io connection. Useful for accessing request headers such as Cookie
or User-Agent
.