Top Related Projects
WebSocket emulation - Javascript client
Realtime application framework (Node.JS server)
Simple pub/sub messaging for the web
:zap: Primus, the creator god of the transformers & an abstraction layer for real-time to prevent module lock-in.
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
Simple, secure & standards compliant web server for the most demanding of applications
Quick Overview
SocketCluster is a highly scalable real-time framework for Node.js. It provides a pub/sub and RPC system that can scale horizontally across multiple CPU cores and machines. SocketCluster is designed to handle high-throughput, real-time applications with ease.
Pros
- Highly scalable and can handle millions of concurrent connections
- Built-in support for horizontal scaling across multiple CPU cores and machines
- Offers both pub/sub and RPC functionality
- Provides automatic reconnection and error handling
Cons
- Steeper learning curve compared to simpler WebSocket libraries
- Documentation can be overwhelming for beginners
- Requires more setup and configuration for complex use cases
- May be overkill for small-scale applications
Code Examples
- Creating a SocketCluster server:
const SocketCluster = require('socketcluster');
const socketCluster = SocketCluster.create({
workers: 4,
brokers: 1,
port: 8000,
appName: 'myapp',
workerController: __dirname + '/worker.js',
brokerController: __dirname + '/broker.js',
socketChannelLimit: 1000,
rebootWorkerOnCrash: true
});
- Subscribing to a channel and handling events:
const socket = socketClusterClient.create();
socket.subscribe('news').watch((data) => {
console.log('Received news:', data);
});
socket.on('error', (error) => {
console.error('Socket error:', error);
});
- Publishing to a channel:
// On the server
scServer.exchange.publish('news', { headline: 'Breaking news!' });
// On the client
socket.publish('news', { headline: 'Client-side update' });
- Making an RPC call:
// On the server
scServer.procedure('multiply', (data, res) => {
res(null, data.a * data.b);
});
// On the client
socket.invoke('multiply', { a: 5, b: 10 }).then((result) => {
console.log('Result:', result); // Output: Result: 50
});
Getting Started
-
Install SocketCluster:
npm install socketcluster
-
Create a basic server (server.js):
const SocketCluster = require('socketcluster'); const socketCluster = SocketCluster.create({ workers: 1, brokers: 1, port: 8000, appName: 'myapp', workerController: __dirname + '/worker.js', brokerController: __dirname + '/broker.js' });
-
Create a worker file (worker.js):
module.exports.run = function (worker) { console.log('Worker started'); worker.scServer.on('connection', (socket) => { console.log('Client connected'); }); };
-
Create a broker file (broker.js):
module.exports.run = function (broker) { console.log('Broker started'); };
-
Run the server:
node server.js
Competitor Comparisons
WebSocket emulation - Javascript client
Pros of sockjs-client
- Simpler API and easier to use for basic WebSocket-like functionality
- Better cross-browser compatibility, including fallback options for older browsers
- Lighter weight and smaller footprint
Cons of sockjs-client
- Less scalable for large-scale, real-time applications
- Fewer built-in features for advanced use cases (e.g., pub/sub, authentication)
- Limited server-side implementation options compared to SocketCluster
Code Comparison
sockjs-client:
var sock = new SockJS('http://localhost:8080/echo');
sock.onopen = function() {
console.log('open');
sock.send('test');
};
sock.onmessage = function(e) {
console.log('message', e.data);
};
SocketCluster:
var socket = socketCluster.create({
hostname: 'localhost',
port: 8000
});
socket.on('connect', function () {
console.log('Connected to server');
socket.emit('sampleClientEvent', {message: 'Hello, server!'});
});
Both libraries provide WebSocket-like functionality, but SocketCluster offers more advanced features out of the box. sockjs-client is simpler and focuses on providing a consistent WebSocket-like API across browsers, while SocketCluster is designed for building more complex, scalable real-time applications.
Realtime application framework (Node.JS server)
Pros of Socket.IO
- Wider adoption and larger community support
- Built-in fallback mechanisms for older browsers
- Extensive documentation and examples
Cons of Socket.IO
- Less scalable for high-traffic applications
- Limited built-in clustering support
- Higher overhead due to additional features
Code Comparison
Socket.IO:
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);
});
});
SocketCluster:
const socketClusterServer = require('socketcluster-server');
const agServer = socketClusterServer.listen(3000);
agServer.on('connection', (socket) => {
console.log('A user connected');
socket.on('chat', (data) => {
agServer.exchange.publish('chatChannel', data);
});
});
Key Differences
- SocketCluster is designed for better scalability and performance in high-traffic scenarios
- Socket.IO offers more built-in features and easier setup for simple applications
- SocketCluster provides native support for horizontal scaling and clustering
- Socket.IO has better compatibility with older browsers and networks
Use Cases
- Socket.IO: Ideal for small to medium-sized applications, prototypes, and projects requiring broad browser support
- SocketCluster: Better suited for large-scale, high-performance applications and microservices architectures
Simple pub/sub messaging for the web
Pros of Faye
- Simpler architecture, making it easier to set up and use for basic pub/sub scenarios
- Supports multiple transport protocols (WebSocket, EventSource, long-polling)
- Well-established project with a longer history and stable API
Cons of Faye
- Less scalable for high-traffic applications compared to SocketCluster
- Fewer built-in features for real-time data synchronization and pub/sub
- Less active development and community support in recent years
Code Comparison
Faye (server-side):
var faye = require('faye');
var server = new faye.NodeAdapter({mount: '/faye', timeout: 45});
server.attach(httpServer);
SocketCluster (server-side):
const SocketCluster = require('socketcluster');
const socketCluster = new SocketCluster({
workers: 4,
brokers: 1,
port: 8000,
appName: 'myapp'
});
Both Faye and SocketCluster are real-time communication libraries for Node.js, but they have different focuses and architectures. Faye is simpler and easier to set up for basic pub/sub scenarios, while SocketCluster is designed for more scalable and feature-rich real-time applications. SocketCluster offers better support for horizontal scaling and has more active development, making it potentially more suitable for large-scale projects. However, Faye's simplicity and support for multiple transport protocols may be advantageous for smaller applications or those requiring broader client compatibility.
:zap: Primus, the creator god of the transformers & an abstraction layer for real-time to prevent module lock-in.
Pros of Primus
- More flexible with multiple transport options (WebSockets, Engine.IO, SockJS, etc.)
- Simpler API and easier to get started with
- Better backward compatibility and fallback mechanisms
Cons of Primus
- Less scalable for large-scale, real-time applications
- Fewer built-in features for horizontal scaling and load balancing
- Less focus on performance optimization for high-concurrency scenarios
Code Comparison
Primus:
const Primus = require('primus');
const server = require('http').createServer();
const primus = new Primus(server, { transformer: 'websockets' });
primus.on('connection', (spark) => {
spark.write('Hello client');
});
SocketCluster:
const SocketCluster = require('socketcluster');
const socketCluster = new SocketCluster({
workers: 4,
brokers: 1,
port: 8000,
appName: 'myapp'
});
socketCluster.on('connection', (socket) => {
socket.emit('hello', 'Hello client');
});
Both Primus and SocketCluster are real-time communication libraries for Node.js, but they have different focuses. Primus emphasizes flexibility and ease of use, while SocketCluster is designed for scalability and high-performance applications. The choice between them depends on the specific requirements of your project, such as the expected number of concurrent connections, scalability needs, and desired features.
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
Pros of ws
- Lightweight and minimalistic, focusing solely on WebSocket implementation
- High performance and low latency
- Extensive browser support
Cons of ws
- Lacks built-in features for scaling and clustering
- Requires additional libraries for advanced functionality like pub/sub or authentication
Code Comparison
ws:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
SocketCluster:
const socketClusterServer = require('socketcluster-server');
const httpServer = require('http').createServer();
const scServer = socketClusterServer.attach(httpServer);
scServer.on('connection', function (socket) {
socket.on('sampleEvent', function (data) {
console.log('Received:', data);
});
});
Key Differences
- ws is a low-level WebSocket implementation, while SocketCluster provides a more comprehensive real-time framework
- SocketCluster offers built-in scaling and clustering capabilities, which ws lacks
- ws requires less setup for basic WebSocket functionality, while SocketCluster provides more out-of-the-box features for complex applications
Use Cases
- ws: Ideal for projects requiring a lightweight WebSocket implementation with minimal overhead
- SocketCluster: Better suited for large-scale, real-time applications that need built-in scaling and advanced features
Simple, secure & standards compliant web server for the most demanding of applications
Pros of uWebSockets
- Higher performance and lower latency
- More lightweight and efficient memory usage
- Better scalability for handling large numbers of concurrent connections
Cons of uWebSockets
- Less feature-rich compared to SocketCluster
- Steeper learning curve for developers new to low-level networking
- Limited built-in support for horizontal scaling
Code Comparison
SocketCluster example:
const scServer = require('socketcluster-server');
let httpServer = require('http').createServer();
let scServer = scServer.attach(httpServer);
scServer.on('connection', (socket) => {
console.log('Client connected');
});
uWebSockets example:
#include <uwebsockets/App.h>
int main() {
uWS::App().ws<PerSocketData>("/*", {
.open = [](auto *ws) {
std::cout << "Client connected" << std::endl;
}
}).listen(9001, [](auto *listen_socket) {
if (listen_socket) {
std::cout << "Listening on port 9001" << std::endl;
}
}).run();
}
Both libraries provide WebSocket functionality, but uWebSockets offers lower-level control and higher performance, while SocketCluster provides a more feature-rich and developer-friendly environment. The choice between them depends on specific project requirements and performance needs.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
SocketCluster
Toolset and boilerplate for quickly creating systems using SocketCluster. See the client and server repos for documentation:
- https://github.com/SocketCluster/socketcluster-client
- https://github.com/SocketCluster/socketcluster-server
Documentation for SCC (horizontally scalable cluster) is available at https://github.com/SocketCluster/socketcluster/blob/master/scc-guide.md
Installation
Setup the socketcluster
command:
npm install -g socketcluster
or:
sudo npm install -g socketcluster
then:
socketcluster create myapp
Once it's installed, go to your new myapp/ directory and launch with:
node server
Access at URL http://localhost:8000/
Node.js v10.0.0
or above is recommended but you can also use SocketCluster with older Node.js versions if you use while
loops instead of for-await-of
loops.
Compatibility mode
For compatibility with existing SocketCluster clients, set the protocolVersion
to 1
and make sure that the path
matches your old client path:
let agServer = socketClusterServer.attach(httpServer, {
protocolVersion: 1,
path: '/socketcluster/'
});
Change log
See the 'releases' section for changes: https://github.com/SocketCluster/socketcluster/releases
License
(The MIT License)
Copyright (c) 2013-2023 SocketCluster.io
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.
Top Related Projects
WebSocket emulation - Javascript client
Realtime application framework (Node.JS server)
Simple pub/sub messaging for the web
:zap: Primus, the creator god of the transformers & an abstraction layer for real-time to prevent module lock-in.
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
Simple, secure & standards compliant web server for the most demanding of applications
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot