Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
socket.io
Advanced tools
The socket.io npm package enables real-time, bidirectional and event-based communication between web clients and servers. It is primarily used to build real-time web applications and has features like broadcasting to multiple sockets, storing data associated with each client, and asynchronous I/O.
Real-time bidirectional event-based communication
This feature allows the server to establish a WebSocket connection with the client for real-time communication. The server listens for events like 'connection', 'chat message', and 'disconnect' to react accordingly.
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
Broadcasting
Broadcasting allows a server to send a message to all connected clients except for the one that triggered the message. This is useful for notifying all users about the actions of one.
io.on('connection', (socket) => {
socket.broadcast.emit('user connected', 'A new user has joined the chat');
});
Namespaces and Rooms
Socket.IO allows for the creation of Namespaces and Rooms which can be used to divide the clients into different groups for targeted broadcasting and communication.
const chat = io.of('/chat').on('connection', (socket) => {
socket.join('some room');
chat.to('some room').emit('some event');
});
The 'ws' package is a simple WebSocket library for Node.js. Unlike socket.io, it does not provide high-level features like broadcasting to multiple sockets or automatic reconnection.
Engine.io is the low-level engine that powers socket.io. It provides the bare WebSocket-like API and is responsible for handling the transport logistics. It is less feature-rich compared to socket.io.
SockJS is a JavaScript library that provides a WebSocket-like object. It is similar to socket.io in that it offers a fallback mechanism for environments where WebSockets are not supported.
Faye is a set of tools for simple publish-subscribe messaging between web clients. It's more focused on the pub/sub paradigm and lacks some of the real-time communication features that socket.io offers.
The following example attaches socket.io to a plain Node.JS
HTTP server listening on port 3000
.
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(3000);
var io = require('socket.io')();
io.on('connection', function(socket){});
io.listen(3000);
Starting with 3.0, express applications have become request handler
functions that you pass to http
or http
Server
instances. You need
to pass the Server
to socket.io
, and not the express application
function.
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
Like Express.JS, Koa works by exposing an application as a request
handler function, but only by calling the callback
method.
var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
Exposed by require('socket.io')
.
Creates a new Server
. Works with and without new
:
var io = require('socket.io')();
// or
var Server = require('socket.io');
var io = new Server();
Optionally, the first or second argument (see below) of the Server
constructor can be an options object.
The following options are supported:
serveClient
sets the value for Server#serveClient()path
sets the value for Server#path()The same options passed to socket.io are always passed to
the engine.io
Server
that gets created. See engine.io
options
as reference.
Creates a new Server
and attaches it to the given srv
. Optionally
opts
can be passed.
Binds socket.io to a new http.Server
that listens on port
.
If v
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.
// 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);
If no arguments are supplied this method returns the current value.
Sets the path v
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.
Sets the adapter v
. 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.
Sets the allowed origins v
. Defaults to any origins being allowed.
If no arguments are supplied this method returns the current value.
Sets the allowed origins as dynamic function. Function takes two arguments origin:String
and callback(error, success)
, where success
is a boolean value indicating whether origin is allowed or not.
Potential drawbacks:
origin
it may have value of *
socket.io
is used together with Express
, the CORS headers will be affected only for socket.io
requests. For Express can use corsThe default (/
) namespace.
Attaches the Server
to an engine.io instance on srv
with the
supplied opts
(optionally).
Attaches the Server
to an engine.io instance that is bound to port
with the given opts
(optionally).
Synonym of Server#attach
.
Advanced use only. Binds the server to a specific engine.io Server
(or compatible API) instance.
Advanced use only. Creates a new socket.io
client from the incoming
engine.io (or compatible API) socket
.
Initializes and retrieves the given Namespace
by its pathname
identifier nsp
.
If the namespace was already initialized it returns it right away.
Emits an event to all connected clients. The following two are equivalent:
var io = require('socket.io')();
io.sockets.emit('an event sent to all connected clients');
io.emit('an event sent to all connected clients');
For other available methods, see Namespace
below.
Closes socket server
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);
See Namespace#use
below.
Represents a pool of sockets connected under a given scope identified
by a pathname (eg: /chat
).
By default the client always connects to /
.
connection
/ connect
. Fired upon a connection.
Parameters:
Socket
the incoming socket.The namespace identifier property.
Hash of Socket
objects that are connected to this namespace indexed
by id
.
Gets a list of client IDs connected to this namespace (across all nodes if applicable).
An example to get all clients in a namespace:
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]
});
Registers a middleware, which is a function that gets executed for
every incoming Socket
and receives as parameter the socket and a
function to optionally defer execution to the next registered
middleware.
var io = require('socket.io')();
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
Errors passed to middleware callbacks are sent as special error
packets to clients.
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.
A hash of strings identifying the rooms this socket is in, indexed by room name.
A reference to the underlying Client
object.
A reference to the underlying Client
transport connection (engine.io
Socket
object).
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
.
A unique identifier for the socket session, that comes from the
underlying Client
.
Emits an event to the socket identified by the string name
. Any
other parameters can be included.
All datastructures are supported, including Buffer
. JavaScript
functions can't be serialized/deserialized.
var io = require('socket.io')();
io.on('connection', function(socket){
socket.emit('an event', { some: 'data' });
});
Adds the socket to the room
, and fires optionally a callback fn
with err
signature (if any).
The socket is automatically a member of a room identified with its
session id (see Socket#id
).
The mechanics of joining rooms are handled by the Adapter
that has been configured (see Server#adapter
above), defaulting to
socket.io-adapter.
Removes the socket from room
, and fires optionally a callback fn
with err
signature (if any).
Rooms are left automatically upon disconnection.
The mechanics of leaving rooms are handled by the Adapter
that has been configured (see Server#adapter
above), defaulting to
socket.io-adapter.
Sets a modifier for a subsequent event emission that the event will
only be broadcasted to sockets 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(socket){
socket.to('others').emit('an event', { some: 'data' });
});
Same as Socket#to
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.
var io = require('socket.io')();
io.on('connection', function(socket){
socket.compress(false).emit('an event', { some: 'data' });
});
The Client
class represents an incoming transport (engine.io)
connection. A Client
can be associated with many multiplexed Socket
that belong to different Namespace
s.
A reference to the underlying engine.io
Socket
connection.
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
.
Socket.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 Socket.IO's debugging scopes you can use:
DEBUG=socket.io* node myapp
MIT
FAQs
node.js realtime framework server
The npm package socket.io receives a total of 0 weekly downloads. As such, socket.io popularity was classified as not popular.
We found that socket.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
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.