Engine.IO
is the implementation of transport-based
cross-browser/cross-device bi-directional communication layer for
Socket.IO.
const engine = require('engine.io');
const server = engine.listen(80);
server.on('connection', socket => {
socket.send('utf 8 string');
socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
});
const engine = require('engine.io');
const http = require('http').createServer().listen(3000);
const server = engine.attach(http);
server.on('connection', socket => {
socket.on('message', data => { });
socket.on('close', () => { });
});
const engine = require('engine.io');
const server = new engine.Server();
server.on('connection', socket => {
socket.send('hi');
});
// …
httpServer.on('upgrade', (req, socket, head) => {
server.handleUpgrade(req, socket, head);
});
httpServer.on('request', (req, res) => {
server.handleRequest(req, res);
});
<script src="/path/to/engine.io.js"></script>
<script>
const socket = new eio.Socket('ws://localhost/');
socket.on('open', () => {
socket.on('message', data => {});
socket.on('close', () => {});
});
</script>
For more information on the client refer to the engine-client repository.
- Maximum reliability. Connections are established even in the presence of:
- proxies and load balancers.
- personal firewall and antivirus software.
- for more information refer to Goals and Architecture sections
- Minimal client size aided by:
- lazy loading of flash transports.
- lack of redundant transports.
- Scalable
- load balancer friendly
- Future proof
- 100% Node.JS core style
- No API sugar (left for higher level projects)
- Written in readable vanilla JavaScript
These are exposed by require('engine.io')
:
flush
- Called when a socket buffer is being flushed.
- Arguments
Socket
: socket being flushedArray
: write buffer
drain
- Called when a socket buffer is drained
- Arguments
Socket
: socket being flushed
protocol
(Number): protocol revision numberServer
: Server class constructorSocket
: Socket class constructorTransport
(Function): transport constructortransports
(Object): map of available transports
-
()
- Returns a new
Server
instance. If the first argument is anhttp.Server
then the newServer
instance will be attached to it. Otherwise, the arguments are passed directly to theServer
constructor. - Parameters
http.Server
: optional, server to attach to.Object
: optional, options object (seeServer#constructor
api docs below)
The following are identical ways to instantiate a server and then attach it.
- Returns a new
const httpServer; // previously created with `http.createServer();` from node.js api.
// create a server first, and then attach
const eioServer = require('engine.io').Server();
eioServer.attach(httpServer);
// or call the module as a function to get `Server`
const eioServer = require('engine.io')();
eioServer.attach(httpServer);
// immediately attach
const eioServer = require('engine.io')(httpServer);
// with custom options
const eioServer = require('engine.io')(httpServer, {
maxHttpBufferSize: 1e3
});
listen
- Creates an
http.Server
which listens on the given port and attaches WS to it. It returns501 Not Implemented
for regular http requests. - Parameters
Number
: port to listen on.Object
: optional, options objectFunction
: callback forlisten
.
- Options
- All options from
Server.attach
method, documented below. - Additionally See Server
constructor
below for options you can pass for creating the new Server
- All options from
- Returns
Server
- Creates an
const engine = require('engine.io');
const server = engine.listen(3000, {
pingTimeout: 2000,
pingInterval: 10000
});
server.on('connection', /* ... */);
attach
- Captures
upgrade
requests for ahttp.Server
. In other words, makes a regular http.Server WebSocket-compatible. - Parameters
http.Server
: server to attach to.Object
: optional, options object
- Options
- All options from
Server.attach
method, documented below. - Additionally See Server
constructor
below for options you can pass for creating the new Server
- All options from
- Returns
Server
a new Server instance.
- Captures
const engine = require('engine.io');
const httpServer = require('http').createServer().listen(3000);
const server = engine.attach(httpServer, {
wsEngine: require('eiows').Server // requires having eiows as dependency
});
server.on('connection', /* ... */);
The main server/manager. Inherits from EventEmitter.
-
connection
- Fired when a new connection is established.
- Arguments
Socket
: a Socket object
-
initial_headers
- Fired on the first request of the connection, before writing the response headers
- Arguments
headers
(Object
): a hash of headersreq
(http.IncomingMessage
): the request
-
headers
- Fired on the all requests of the connection, before writing the response headers
- Arguments
headers
(Object
): a hash of headersreq
(http.IncomingMessage
): the request
-
connection_error
- Fired when an error occurs when establishing the connection.
- Arguments
error
: an object with following properties:req
(http.IncomingMessage
): the request that was droppedcode
(Number
): one ofServer.errors
message
(string
): one ofServer.errorMessages
context
(Object
): extra info about the error
Code | Message |
---|---|
0 | "Transport unknown" |
1 | "Session ID unknown" |
2 | "Bad handshake method" |
3 | "Bad request" |
4 | "Forbidden" |
5 | "Unsupported protocol version" |
Important: if you plan to use Engine.IO in a scalable way, please keep in mind the properties below will only reflect the clients connected to a single process.
clients
(Object): hash of connected clients by id.clientsCount
(Number): number of connected clients.
- constructor
- Initializes the server
- Parameters
Object
: optional, options object
- Options
pingTimeout
(Number
): how many ms without a pong packet to consider the connection closed (20000
)pingInterval
(Number
): how many ms before sending a new ping packet (25000
)upgradeTimeout
(Number
): how many ms before an uncompleted transport upgrade is cancelled (10000
)maxHttpBufferSize
(Number
): how many bytes or characters a message can be, before closing the session (to avoid DoS). Default value is1E6
.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.transports
(<Array> String
): transports to allow connections to (['polling', 'websocket']
)allowUpgrades
(Boolean
): whether to allow transport upgrades (true
)perMessageDeflate
(Object|Boolean
): parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set totrue
to enable. (defaults tofalse
)threshold
(Number
): data is compressed only if the byte size is above this value (1024
)
httpCompression
(Object|Boolean
): parameters of the http compression for the polling transports (see zlib api docs). Set tofalse
to disable. (true
)threshold
(Number
): data is compressed only if the byte size is above this value (1024
)
cookie
(Object|Boolean
): configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie might be used for sticky-session. Defaults to not sending any cookie (false
). See here for all supported options.wsEngine
(Function
): what WebSocket server implementation to use. Specified module must conform to thews
interface (see ws module api docs). Default value isws
. An alternative c++ addon is also available by installingeiows
module.cors
(Object
): the options that will be forwarded to the cors module. See there for all available options. Defaults to no CORS allowed.initialPacket
(Object
): an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.allowEIO3
(Boolean
): whether to support v3 Engine.IO clients (defaults tofalse
)
close
- Closes all clients
- Returns
Server
for chaining
handleRequest
- Called internally when a
Engine
request is intercepted. - Parameters
http.IncomingMessage
: a node request objecthttp.ServerResponse
: a node response object
- Returns
Server
for chaining
- Called internally when a
handleUpgrade
- Called internally when a
Engine
ws upgrade is intercepted. - Parameters (same as
upgrade
event)http.IncomingMessage
: a node request objectnet.Stream
: TCP socket for the requestBuffer
: legacy tail bytes
- Returns
Server
for chaining
- Called internally when a
attach
- Attach this Server instance to an
http.Server
- Captures
upgrade
requests for ahttp.Server
. In other words, makes a regular http.Server WebSocket-compatible. - Parameters
http.Server
: server to attach to.Object
: optional, options object
- Options
path
(String
): name of the path to capture (/engine.io
).destroyUpgrade
(Boolean
): destroy unhandled upgrade requests (true
)destroyUpgradeTimeout
(Number
): milliseconds after which unhandled requests are ended (1000
)
- Attach this Server instance to an
generateId
- Generate a socket id.
- Overwrite this method to generate your custom socket id.
- Parameters
http.IncomingMessage
: a node request object
- Returns A socket id for connected client.
A representation of a client. Inherits from EventEmitter.
close
- Fired when the client is disconnected.
- Arguments
String
: reason for closingObject
: description object (optional)
message
- Fired when the client sends a message.
- Arguments
String
orBuffer
: Unicode string or Buffer with binary contents
error
- Fired when an error occurs.
- Arguments
Error
: error object
flush
- Called when the write buffer is being flushed.
- Arguments
Array
: write buffer
drain
- Called when the write buffer is drained
packet
- Called when a socket received a packet (
message
,ping
) - Arguments
type
: packet typedata
: packet data (if type is message)
- Called when a socket received a packet (
packetCreate
- Called before a socket sends a packet (
message
,ping
) - Arguments
type
: packet typedata
: packet data (if type is message)
- Called before a socket sends a packet (
id
(String): unique identifierserver
(Server): engine parent referencerequest
(http.IncomingMessage): request that originated the Socketupgraded
(Boolean): whether the transport has been upgradedreadyState
(String): opening|open|closing|closedtransport
(Transport): transport reference
send
:- Sends a message, performing
message = toString(arguments[0])
unless sending binary data, which is sent as is. - Parameters
String
|Buffer
|ArrayBuffer
|ArrayBufferView
: a string or any object implementingtoString()
, with outgoing data, or a Buffer or ArrayBuffer with binary data. Also any ArrayBufferView can be sent as is.Object
: optional, options objectFunction
: optional, a callback executed when the message gets flushed out by the transport
- Options
compress
(Boolean
): whether to compress sending data. This option might be ignored and forced to betrue
when using polling. (true
)
- Returns
Socket
for chaining
- Sends a message, performing
close
- Disconnects the client
- Returns
Socket
for chaining
Exposed in the eio
global namespace (in the browser), or by
require('engine.io-client')
(in Node.JS).
For the client API refer to the engine-client repository.
Engine.IO is powered by debug.
In order to see all the debug output, run your app with the environment variable
DEBUG
including the desired scope.
To see the output from all of Engine.IO's debugging scopes you can use:
DEBUG=engine* node myapp
polling
: XHR / JSONP polling transport.websocket
: WebSocket transport.