Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Websocket Client & Server Library tracking the latest protocol drafts from the IETF.
The 'websocket' npm package provides a WebSocket server and client for Node.js, allowing for real-time, bidirectional communication between a client and server over a single, long-lived connection.
WebSocket Server
This code sets up a basic WebSocket server using the 'websocket' package. It listens for incoming WebSocket connections, accepts them, and allows for message exchange between the server and connected clients.
const WebSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer((request, response) => {
response.writeHead(404);
response.end();
});
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', (request) => {
const connection = request.accept(null, request.origin);
console.log('Connection accepted.');
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF('Hello from server!');
}
});
connection.on('close', (reasonCode, description) => {
console.log('Peer ' + connection.remoteAddress + ' disconnected.');
});
});
WebSocket Client
This code demonstrates how to create a WebSocket client using the 'websocket' package. The client connects to a WebSocket server, handles connection events, and sends random numbers to the server at regular intervals.
const WebSocketClient = require('websocket').client;
const client = new WebSocketClient();
client.on('connectFailed', (error) => {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', (connection) => {
console.log('WebSocket Client Connected');
connection.on('error', (error) => {
console.log('Connection Error: ' + error.toString());
});
connection.on('close', () => {
console.log('Connection Closed');
});
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received: ' + message.utf8Data);
}
});
function sendNumber() {
if (connection.connected) {
const number = Math.round(Math.random() * 0xFFFFFF);
connection.sendUTF(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
});
client.connect('ws://localhost:8080/', 'echo-protocol');
The 'ws' package is a popular WebSocket implementation for Node.js. It is known for its performance and simplicity. Compared to 'websocket', 'ws' is more lightweight and has a larger community, making it a preferred choice for many developers.
The 'socket.io' package provides a WebSocket-like API but with additional features such as fallback to HTTP long-polling, automatic reconnection, and rooms/namespaces support. It is more feature-rich compared to 'websocket' and is suitable for applications requiring more advanced real-time communication capabilities.
WARNING: This is a library implementing only the most recent draft of the WebSocket protocol. It will not work with production browsers until new versions are released that support it.
Note about FireFox 6: Firefox 6 re-enables support for WebSockets by default. It uses a prefixed constructor name, MozWebSocket(), to avoid conflicting with already deployed scripts. It also implements draft-07, so if you want to target Firefox 6, you will need to checkout my draft-07 branch, not the latest one.
If you need to simultaneously support older production browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1148686
This code is currently unproven. It should be considered alpha quality, and is not recommended for production use, though it is used in production on worlize.com. Your mileage may vary.
This is a pure JavaScript implementation of the WebSocket protocol version 8 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test" folder.
For a WebSocket draft-08/-09/-10 client written in Flash see my AS3WebScocket project.
The latest three drafts of the WebSocket protocol, draft-08, draft-09, and draft-10, are functionally identical and implement the same wire protocol, protocol version "8". They are all interoperable, with only editorial changes across the three drafts. The current implementation of WebSocket-Node works with all three.
If you're looking for the version supporting draft-07 or draft-06, see the draft-07 or draft-06 branches. Previous draft branches will not be maintained, as I plan to track each subsequent draft of the protocol until it's finalized, and will ultimately be supporting only the final draft.
Tested against Node version 0.4.7. It may work in earlier versions but I haven't tried it. YMMV.
For more complete documentation, see the Documentation Wiki.
In your project root:
$ npm install websocket
Then in your code:
var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var WebSocketFrame = require('websocket').frame;
var WebSocketRouter = require('websocket').router;
Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + " Received request for " + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + " Server is listening on port 8080");
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true
});
wsServer.on('connect', function(connection) {
console.log((new Date()) + " Connection accepted.");
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received Message: " + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log("Received Binary Message of " + message.binaryData.length + " bytes");
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(connection) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
});
This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
#!/usr/bin/env node
var WebSocketClient = require('websocket').client;
var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log("Connect Error: " + error.toString());
});
client.on('connect', function(connection) {
console.log("WebSocket client connected");
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log("echo-protocol Connection Closed");
})
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
function sendNumber() {
if (connection.connected) {
var number = Math.round(Math.random() * 0xFFFFFF);
connection.sendUTF(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
});
client.connect("ws://localhost:8080/", 'echo-protocol');
For an example of using the request router, see libwebsockets-test-server.js
in the test
folder.
A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. WebSockets: The Real-Time Web, Delivered
FAQs
Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.
We found that websocket demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.