Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
engine.io
Advanced tools
The realtime engine behind Socket.IO. Provides the foundation of a bidirectional connection between client and server
The engine.io npm package is a core component for building real-time web applications. It is designed to be efficient and includes a robust WebSocket and polling implementation. Engine.io provides a low-level API that handles the WebSocket connections, including fallbacks to alternative protocols if WebSockets are not supported by the client or server environments. This makes it an excellent choice for developing applications that require real-time bidirectional event-based communication.
Server Initialization
This feature allows you to initialize an engine.io server. You can listen for connections and handle messages and disconnections from clients.
const { Server } = require('engine.io');
const server = new Server({ /* options */ });
server.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (data) => {
console.log(data);
});
socket.on('close', () => {
console.log('user disconnected');
});
});
Client Initialization
This feature demonstrates how to initialize a connection to an engine.io server from the client side. It includes handling open, message, and close events.
const { Socket } = require('engine.io-client');
const socket = new Socket('ws://localhost');
socket.on('open', () => {
console.log('connection established');
socket.send('Hello server!');
});
socket.on('message', (data) => {
console.log(data);
});
socket.on('close', () => {
console.log('connection closed');
});
Socket.io is a library that enables real-time, bidirectional and event-based communication between web clients and servers. It builds on top of engine.io by adding additional features such as namespaces and rooms, making it more suitable for building complex real-time applications. While engine.io focuses on the core transport mechanism, socket.io provides a higher-level API.
The 'ws' package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Unlike engine.io, which provides automatic fallbacks and a protocol designed to work in all network conditions, 'ws' focuses purely on WebSocket communication. This makes 'ws' a good choice for environments where WebSockets are supported and you need a lightweight, more focused implementation.
Faye-websocket is a WebSocket client and server implementation that aims to provide a simple interface for working with WebSockets and EventSource. It is more similar to 'ws' in its focus on WebSockets but, like engine.io, it also supports client and server roles. However, it does not include the automatic protocol fallback mechanism that engine.io offers.
Engine.IO
is the implementation of transport-based
cross-browser/cross-device bi-directional communication layer for
Socket.IO.
var engine = require('engine.io');
var server = engine.listen(80);
server.on('connection', function(socket){
socket.send('utf 8 string');
socket.send(new Buffer([0, 1, 2, 3, 4, 5])); // binary data
});
var engine = require('engine.io');
var http = require('http').createServer().listen(3000);
var server = engine.attach(http);
server.on('connection', function (socket) {
socket.on('message', function(data){ });
socket.on('close', function(){ });
});
var engine = require('engine.io');
var server = new engine.Server();
server.on('connection', function(socket){
socket.send('hi');
});
// …
httpServer.on('upgrade', function(req, socket, head){
server.handleUpgrade(req, socket, head);
});
httpServer.on('request', function(req, res){
server.handleRequest(req, res);
});
<script src="/path/to/engine.io.js"></script>
<script>
var socket = new eio.Socket('ws://localhost/');
socket.on('open', function(){
socket.on('message', function(data){});
socket.on('close', function(){});
});
</script>
For more information on the client refer to the engine-client repository.
These are exposed by require('engine.io')
:
flush
Socket
: socket being flushedArray
: write bufferdrain
Socket
: socket being flushedprotocol
(Number): protocol revision numberServer
: Server class constructorSocket
: Socket class constructorTransport
(Function): transport constructortransports
(Object): map of available transports()
Server
instance. If the first argument is an http.Server
then the
new Server
instance will be attached to it. Otherwise, the arguments are passed
directly to the Server
constructor.http.Server
: optional, server to attach to.Object
: optional, options object (see Server#constructor
api docs below)The following are identical ways to instantiate a server and then attach it.
var httpServer; // previously created with `http.createServer();` from node.js api.
// create a server first, and then attach
var eioServer = require('engine.io').Server();
eioServer.attach(httpServer);
// or call the module as a function to get `Server`
var eioServer = require('engine.io')();
eioServer.attach(httpServer);
// immediately attach
var eioServer = require('engine.io')(httpServer);
listen
http.Server
which listens on the given port and attaches WS
to it. It returns 501 Not Implemented
for regular http requests.Number
: port to listen on.Object
: optional, options objectFunction
: callback for listen
.Server.attach
method, documented below.constructor
below for options you can pass for creating the new ServerServer
attach
upgrade
requests for a http.Server
. In other words, makes
a regular http.Server WebSocket-compatible.http.Server
: server to attach to.Object
: optional, options objectServer.attach
method, documented below.constructor
below for options you can pass for creating the new ServerServer
a new Server instance.The main server/manager. Inherits from EventEmitter.
connection
Socket
: a Socket objectImportant: 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.Object
: optional, options objectpingTimeout
(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
)maxHttpBufferSize
(Number
): how many bytes or characters a message
can be when polling, before closing the session (to avoid DoS). Default
value is 10E7
.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)
, where
success
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
)cookie
(String|Boolean
): name of the HTTP cookie that
contains the client sid to send as part of handshake response
headers. Set to false
to not send one. (io
)close
Server
for chaininghandleRequest
Engine
request is intercepted.http.ServerRequest
: a node request objecthttp.ServerResponse
: a node response objectServer
for chaininghandleUpgrade
Engine
ws upgrade is intercepted.upgrade
event)
http.ServerRequest
: a node request objectnet.Stream
: TCP socket for the requestBuffer
: legacy tail bytesServer
for chainingattach
http.Server
upgrade
requests for a http.Server
. In other words, makes
a regular http.Server WebSocket-compatible.http.Server
: server to attach to.Object
: optional, options objectpath
(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
)A representation of a client. Inherits from EventEmitter.
close
String
: reason for closingObject
: description object (optional)message
String
or Buffer
: Unicode string or Buffer with binary contentserror
Error
: error objectflush
Array
: write bufferdrain
packet
message
, ping
)type
: packet typedata
: packet data (if type is message)packetCreate
message
, pong
)type
: packet typedata
: packet data (if type is message)id
(String): unique identifierserver
(Server): engine parent referencerequest
(http.ServerRequest): request that originated the Socketupgraded
(Boolean): whether the transport has been upgradedreadyState
(String): opening|open|closing|closedtransport
(Transport): transport referencesend
:
message = toString(arguments[0])
unless
sending binary data, which is sent as is.String
| Buffer
| ArrayBuffer
| ArrayBufferView
: a string or any object implementing toString()
, with outgoing data, or a Buffer or ArrayBuffer with binary data. Also any ArrayBufferView can be sent as is.Function
: optional, a callback executed when the message gets flushed out by the transportSocket
for chainingclose
Socket
for chainingExposed 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.The support channels for engine.io
are the same as socket.io
:
To contribute patches, run tests or benchmarks, make sure to clone the repository:
git clone git://github.com/LearnBoost/engine.io.git
Then:
cd engine.io
npm install
Tests run with make test
. It runs the server tests that are aided by
the usage of engine.io-client
.
Make sure npm install
is run first.
The main goal of Engine
is ensuring the most reliable realtime communication.
Unlike the previous Socket.IO core, it always establishes a long-polling
connection first, then tries to upgrade to better transports that are "tested" on
the side.
During the lifetime of the Socket.IO projects, we've found countless drawbacks
to relying on HTML5 WebSocket
or Flash Socket
as the first connection
mechanisms.
Both are clearly the right way of establishing a bidirectional communication, with HTML5 WebSocket being the way of the future. However, to answer most business needs, alternative traditional HTTP 1.1 mechanisms are just as good as delivering the same solution.
WebSocket based connections have two fundamental benefits:
Engine
connection. This negatively impacts RAM and CPU usage.Better user experience
Due to the reasons stated in point 1, the most important effect of being able to establish a WebSocket connection is raw data transfer speed, which translates in some cases in better user experience.
Applications with heavy realtime interaction (such as games) will benefit greatly, whereas applications like realtime chat (Gmail/Facebook), newsfeeds (Facebook) or timelines (Twitter) will have negligible user experience improvements.
Having said this, attempting to establish a WebSocket connection directly so far has proven problematic:
Proxies
Many corporate proxies block WebSocket traffic.
Personal firewall and antivirus software
As a result of our research, we've found that at least 3 personal security
applications block WebSocket traffic.
Cloud application platforms
Platforms like Heroku or No.de have had trouble keeping up with the fast-paced
nature of the evolution of the WebSocket protocol. Applications therefore end up
inevitably using long polling, but the seamless installation experience of
Socket.IO we strive for ("require() it and it just works") disappears.
Some of these problems have solutions. In the case of proxies and personal programs, however, the solutions many times involve upgrading software. Experience has shown that relying on client software upgrades to deliver a business solution is fruitless: the very existence of this project has to do with a fragmented panorama of user agent distribution, with clients connecting with latest versions of the most modern user agents (Chrome, Firefox and Safari), but others with versions as low as IE 5.5.
From the user perspective, an unsuccessful WebSocket connection can translate in up to at least 10 seconds of waiting for the realtime application to begin exchanging data. This perceptively hurts user experience.
To summarize, Engine focuses on reliability and user experience first, marginal
potential UX improvements and increased server performance second. Engine
is the
result of all the lessons learned with WebSocket in the wild.
The main premise of Engine
, and the core of its existence, is the ability to
swap transports on the fly. A connection starts as xhr-polling, but it can
switch to WebSocket.
The central problem this poses is: how do we switch transports without losing messages?
Engine
only switches from polling to another transport in between polling
cycles. Since the server closes the connection after a certain timeout when
there's no activity, and the polling transport implementation buffers messages
in between connections, this ensures no message loss and optimal performance.
Another benefit of this design is that we workaround almost all the limitations of Flash Socket, such as slow connection times, increased file size (we can safely lazy load it without hurting user experience), etc.
Absolutely. Although the recommended framework for building realtime applications is Socket.IO, since it provides fundamental features for real-world applications such as multiplexing, reconnection support, etc.
Engine
is to Socket.IO what Connect is to Express. An essential piece for building
realtime frameworks, but something you probably won't be using for building
actual applications.
No. The main reason is that Engine
is meant to be bundled with frameworks.
Socket.IO includes Engine
, therefore serving two clients is not necessary. If
you use Socket.IO, including
<script src="/socket.io/socket.io.js">
has you covered.
Engine
in other languages?Absolutely. The engine.io-protocol repository contains the most up to date description of the specification at all times, and the parser implementation in JavaScript.
(The MIT License)
Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
The realtime engine behind Socket.IO. Provides the foundation of a bidirectional connection between client and server
The npm package engine.io receives a total of 5,528,927 weekly downloads. As such, engine.io popularity was classified as popular.
We found that engine.io demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.