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.
Socket.IO is a Node.JS project that makes WebSockets and realtime possible in all browsers. It also enhances WebSockets by providing built-in multiplexing, horizontal scalability, automatic JSON encoding/decoding, and more.
npm install socket.io
First, require socket.io
:
var io = require('socket.io');
Next, attach it to a HTTP/HTTPS server. If you're using the fantastic express
web framework:
var app = express.createServer();
, io = io.listen(app);
app.listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Finally, load it from the client side code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
For more thorough examples, look at the examples/
directory.
Socket.IO allows you to emit and receive custom events.
Besides connect
, message
and disconnect
, you can emit custom events:
// note, io.listen(<port>) will create a http server for you
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone');
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
sockets.emit('user disconnected');
});
});
Sometimes it's necessary to store data associated with a client that's necessary for the duration of the session.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () { socket.emit('ready'); });
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function () {
socket.emit('set nickname', confirm('What is your nickname?'));
socket.on('ready', function () {
console.log('Connected !');
socket.emit('msg', confirm('What is your message?'));
});
});
</script>
If you have control over all the messages and events emitted for a particular
application, using the default /
namespace works.
If you want to leverage 3rd-party code, or produce code to share with others,
socket.io provides a way of namespacing a socket
.
This has the benefit of multiplexing
a single connection. Instead of
socket.io using two WebSocket
connections, it'll use one.
The following example defines a socket that listens on '/chat' and one for '/news':
var io = require('socket.io').listen(80);
var chat = io
.of('/chat');
.on('connection', function (socket) {
socket.emit('a message', { that: 'only', '/chat': 'will get' });
chat.emit('a message', { everyone: 'in', '/chat': 'will get' });
});
var news = io
.of('/news');
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi!');
});
news.on('news', function () {
news.emit('woot');
});
</script>
Sometimes certain messages can be dropped. Let's say you have an app that
shows realtime tweets for the keyword bieber
.
If a certain client is not ready to receive messages (because of network slowness or other issues, or because he's connected through long polling and is in the middle of a request-response cycle), if he doesn't receive ALL the tweets related to bieber your application won't suffer.
In that case, you might want to send those messages as volatile messages.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
var tweets = setInterval(function () {
getBieberTweet(function (tweet) {
socket.volatile.emit('bieber tweet', tweet);
});
}, 100);
socket.on('disconnect', function () {
clearInterval(tweets);
});
});
In the client side, messages are received the same way whether they're volatile or not.
Sometimes, you might want to get a callback when the client confirmed the message reception.
To do this, simply pass a function as the last parameter of .send
or .emit
.
What's more, when you use .emit
, the acknowledgement is done by you, which
means you can also pass data along:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
<script>
var socket = io.connect(); // TIP: .connect with no args does auto-discovery
socket.on('connection', function () {
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
</script>
To broadcast, simply add a broadcast
flag to emit
and send
method calls.
Broadcasting means sending a message to everyone else except for the socket
that starts it.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
socket.broadcast.json.send({ a: 'message' });
});
Sometimes you want to put certain sockets in the same room, so that it's easy to broadcast to all of them together.
Think of this as built-in channels for sockets. Sockets join
and leave
rooms in each socket.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.join('justin bieber fans');
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
});
If you just want the WebSocket semantics, you can do that too.
Simply leverage send
and listen on the message
event:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
<script>
var socket = io.connect('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
Configuration in socket.io is TJ-style:
var io = require('socket.io').listen(80);
io.configure(function () {
io.set('transports', ['websocket', 'flashsocket', 'xhr-polling']);
});
io.configure('development', function () {
io.set('transports', ['websocket', 'xhr-polling']);
io.enable('log');
});
(The MIT License)
Copyright (c) 2011 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
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.