- IO
- io.protocol
- io([url][, options])
- Class: io.Manager
- new Manager(url[, options])
- manager.reconnection([value])
- manager.reconnectionAttempts([value])
- manager.reconnectionDelay([value])
- manager.reconnectionDelayMax([value])
- manager.timeout([value])
- manager.open([callback])
- manager.connect([callback])
- manager.socket(nsp, options)
- Event: 'connect_error'
- Event: 'connect_timeout'
- Event: 'reconnect'
- Event: 'reconnect_attempt'
- Event: 'reconnecting'
- Event: 'reconnect_error'
- Event: 'reconnect_failed'
- Event: 'ping'
- Event: 'pong'
- Class: io.Socket
- socket.id
- socket.connected
- socket.disconnected
- socket.open()
- socket.connect()
- socket.send([...args][, ack])
- socket.emit(eventName[, ...args][, ack])
- socket.on(eventName, callback)
- socket.compress(value)
- socket.binary(value)
- socket.close()
- socket.disconnect()
- Event: 'connect'
- Event: 'connect_error'
- Event: 'connect_timeout'
- Event: 'error'
- Event: 'disconnect'
- Event: 'reconnect'
- Event: 'reconnect_attempt'
- Event: 'reconnecting'
- Event: 'reconnect_error'
- Event: 'reconnect_failed'
- Event: 'ping'
- Event: 'pong'
Exposed as the io
namespace in the standalone build, or the result of calling require('socket.io-client')
.
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost');
</script>
const io = require('socket.io-client');
// or with import syntax
import io from 'socket.io-client';
- (Number)
The protocol revision number.
url
(String) (defaults towindow.location
)options
(Object)forceNew
(Boolean) whether to reuse an existing connection
- Returns
Socket
Creates a new Manager
for the given URL, and attempts to reuse an existing Manager
for subsequent calls, unless the multiplex
option is passed with false
. Passing this option is the equivalent of passing 'force new connection': true
or forceNew: true
.
A new Socket
instance is returned for the namespace specified by the pathname in the URL, defaulting to /
. For example, if the url
is http://localhost/users
, a transport connection will be established to http://localhost
and a Socket.IO connection will be established to /users
.
Query parameters can also be provided, either with the query
option or directly in the url (example: http://localhost/users?token=abc
).
See new Manager(url[, options]) for available options
.
By default, a single connection is used when connecting to different namespaces (to minimize resources):
const socket = io();
const adminSocket = io('/admin');
// a single connection will be established
That behaviour can be disabled with the forceNew
option:
const socket = io();
const adminSocket = io('/admin', { forceNew: true });
// will create two distinct connections
Note: reusing the same namespace will also create two connections
const socket = io();
const socket2 = io();
// will also create two distinct connections
const socket = io('http://localhost', {
path: '/myownpath'
});
// server-side
const io = require('socket.io')({
path: '/myownpath'
});
The request URLs will look like: localhost/myownpath/?EIO=3&transport=polling&sid=<id>
const socket = io('http://localhost/admin', {
path: '/mypath'
});
Here, the socket connects to the admin
namespace, with the custom path mypath
.
The request URLs will look like: localhost/mypath/?EIO=3&transport=polling&sid=<id>
(the namespace is sent as part of the payload).
const socket = io('http://localhost?token=abc');
// server-side
const io = require('socket.io')();
// middleware
io.use((socket, next) => {
let token = socket.handshake.query.token;
if (isValid(token)) {
return next();
}
return next(new Error('authentication error'));
});
// then
io.on('connection', (socket) => {
let token = socket.handshake.query.token;
// ...
});
const socket = io({
query: {
token: 'cde'
}
});
The query content can also be updated on reconnection:
socket.on('reconnect_attempt', () => {
socket.io.opts.query = {
token: 'fgh'
}
});
This only works if polling
transport is enabled (which is the default). Custom headers will not be appended when using websocket
as the transport. This happens because the WebSocket handshake does not honor custom headers. (For background see the WebSocket protocol RFC)
const socket = io({
transportOptions: {
polling: {
extraHeaders: {
'x-clientid': 'abc'
}
}
}
});
// server-side
const io = require('socket.io')();
// middleware
io.use((socket, next) => {
let clientId = socket.handshake.headers['x-clientid'];
if (isValid(clientId)) {
return next();
}
return next(new Error('authentication error'));
});
By default, a long-polling connection is established first, then upgraded to "better" transports (like WebSocket). If you like to live dangerously, this part can be skipped:
const socket = io({
transports: ['websocket']
});
// on reconnection, reset the transports option, as the Websocket
// connection may have failed (caused by proxy, firewall, browser, ...)
socket.on('reconnect_attempt', () => {
socket.io.opts.transports = ['polling', 'websocket'];
});
The default parser promotes compatibility (support for Blob
, File
, binary check) at the expense of performance. A custom parser can be provided to match the needs of your application. Please see the example here.
const parser = require('socket.io-msgpack-parser'); // or require('socket.io-json-parser')
const socket = io({
parser: parser
});
// the server-side must have the same parser, to be able to communicate
const io = require('socket.io')({
parser: parser
});
url
(String)options
(Object)path
(String) name of the path that is captured on the server side (/socket.io
)reconnection
(Boolean) whether to reconnect automatically (true
)reconnectionAttempts
(Number) number of reconnection attempts before giving up (Infinity
)reconnectionDelay
(Number) how long to initially wait before attempting a new reconnection (1000
). Affected by +/-randomizationFactor
, for example the default initial delay will be between 500 to 1500ms.reconnectionDelayMax
(Number) maximum amount of time to wait between reconnections (5000
). Each attempt increases the reconnection delay by 2x along with a randomization as aboverandomizationFactor
(Number) (0.5
), 0 <= randomizationFactor <= 1timeout
(Number) connection timeout before aconnect_error
andconnect_timeout
events are emitted (20000
)autoConnect
(Boolean) by setting this false, you have to callmanager.open
whenever you decide it's appropriatequery
(Object): additional query parameters that are sent when connecting a namespace (then found insocket.handshake.query
object on the server-side)parser
(Parser): the parser to use. Defaults to an instance of theParser
that ships with socket.io. See socket.io-parser.
- Returns
Manager
The options
are also passed to engine.io-client
upon initialization of the underlying Socket
. See the available options
here.
value
(Boolean)- Returns
Manager|Boolean
Sets the reconnection
option, or returns it if no parameters are passed.
value
(Number)- Returns
Manager|Number
Sets the reconnectionAttempts
option, or returns it if no parameters are passed.
value
(Number)- Returns
Manager|Number
Sets the reconnectionDelay
option, or returns it if no parameters are passed.
value
(Number)- Returns
Manager|Number
Sets the reconnectionDelayMax
option, or returns it if no parameters are passed.
value
(Number)- Returns
Manager|Number
Sets the timeout
option, or returns it if no parameters are passed.
callback
(Function)- Returns
Manager
If the manager was initiated with autoConnect
to false
, launch a new connection attempt.
The callback
argument is optional and will be called once the attempt fails/succeeds.
Synonym of manager.open([callback]).
nsp
(String)options
(Object)- Returns
Socket
Creates a new Socket
for the given namespace.
error
(Object) error object
Fired upon a connection error.
Fired upon a connection timeout.
attempt
(Number) reconnection attempt number
Fired upon a successful reconnection.
Fired upon an attempt to reconnect.
attempt
(Number) reconnection attempt number
Fired upon a successful reconnection.
error
(Object) error object
Fired upon a reconnection attempt error.
Fired when couldn't reconnect within reconnectionAttempts
.
Fired when a ping packet is written out to the server.
ms
(Number) number of ms elapsed sinceping
packet (i.e.: latency).
Fired when a pong is received from the server.
- (String)
An unique identifier for the socket session. Set after the connect
event is triggered, and updated after the reconnect
event.
const socket = io('http://localhost');
console.log(socket.id); // undefined
socket.on('connect', () => {
console.log(socket.id); // 'G5p5...'
});
- (Boolean)
Whether or not the socket is connected to the server.
const socket = io('http://localhost');
socket.on('connect', () => {
console.log(socket.connected); // true
});
- (Boolean)
Whether or not the socket is disconnected from the server.
const socket = io('http://localhost');
socket.on('connect', () => {
console.log(socket.disconnected); // false
});
- Returns
Socket
Manually opens the socket.
const socket = io({
autoConnect: false
});
// ...
socket.open();
It can also be used to manually reconnect:
socket.on('disconnect', () => {
socket.open();
});
Synonym of socket.open().
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.
socket.emit('ferret', 'tobi', (data) => {
console.log(data); // data will be 'woot'
});
// server:
// io.on('connection', (socket) => {
// socket.on('ferret', (name, fn) => {
// fn('woot');
// });
// });
eventName
(String)callback
(Function)- Returns
Socket
Register a new handler for the given event.
socket.on('news', (data) => {
console.log(data);
});
// with multiple arguments
socket.on('news', (arg1, arg2, arg3, arg4) => {
// ...
});
// with callback
socket.on('news', (cb) => {
cb(0);
});
The socket actually inherits every method of the Emitter class, like hasListeners
, once
or off
(to remove an event listener).
value
(Boolean)- Returns
Socket
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.
socket.compress(false).emit('an event', { some: 'data' });
Specifies whether the emitted data contains binary. Increases performance when specified. Can be true
or false
.
socket.binary(false).emit('an event', { some: 'data' });
- Returns
Socket
Disconnects the socket manually.
Synonym of socket.close().
Fired upon a connection including a successful reconnection.
socket.on('connect', () => {
// ...
});
// note: you should register event handlers outside of connect,
// so they are not registered again on reconnection
socket.on('myevent', () => {
// ...
});
error
(Object) error object
Fired upon a connection error.
socket.on('connect_error', (error) => {
// ...
});
Fired upon a connection timeout.
socket.on('connect_timeout', (timeout) => {
// ...
});
error
(Object) error object
Fired when an error occurs.
socket.on('error', (error) => {
// ...
});
reason
(String) either 'io server disconnect' or 'io client disconnect'
Fired upon a disconnection.
socket.on('disconnect', (reason) => {
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
socket.connect();
}
// else the socket will automatically try to reconnect
});
attempt
(Number) reconnection attempt number
Fired upon a successful reconnection.
socket.on('reconnect', (attemptNumber) => {
// ...
});
attempt
(Number) reconnection attempt number
Fired upon an attempt to reconnect.
socket.on('reconnect_attempt', (attemptNumber) => {
// ...
});
attempt
(Number) reconnection attempt number
Fired upon an attempt to reconnect.
socket.on('reconnecting', (attemptNumber) => {
// ...
});
error
(Object) error object
Fired upon a reconnection attempt error.
socket.on('reconnect_error', (error) => {
// ...
});
Fired when couldn't reconnect within reconnectionAttempts
.
socket.on('reconnect_failed', () => {
// ...
});
Fired when a ping packet is written out to the server.
socket.on('ping', () => {
// ...
});
ms
(Number) number of ms elapsed sinceping
packet (i.e.: latency).
Fired when a pong is received from the server.
socket.on('pong', (latency) => {
// ...
});