
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
rpc-websockets
Advanced tools
The rpc-websockets package provides a simple way to implement JSON-RPC 2.0 over WebSockets. It allows for both client and server implementations, enabling remote procedure calls (RPC) and event-based communication between clients and servers.
Creating a WebSocket Server
This code demonstrates how to create a WebSocket server using rpc-websockets. The server listens on port 8080 and registers a 'sum' method that takes an array of parameters and returns their sum.
const WebSocketServer = require('rpc-websockets').Server;
const server = new WebSocketServer({ port: 8080 });
server.register('sum', (params) => {
return params[0] + params[1];
});
console.log('WebSocket server is running on ws://localhost:8080');
Creating a WebSocket Client
This code demonstrates how to create a WebSocket client using rpc-websockets. The client connects to the server at ws://localhost:8080 and calls the 'sum' method with parameters 5 and 3, then logs the result.
const WebSocketClient = require('rpc-websockets').Client;
const client = new WebSocketClient('ws://localhost:8080');
client.on('open', () => {
client.call('sum', [5, 3]).then((result) => {
console.log('Sum:', result);
}).catch((error) => {
console.error('Error:', error);
});
});
Subscribing to Events
This code demonstrates how to create a WebSocket server that emits events. The server defines an 'update' event and emits it every second with the current timestamp.
const WebSocketServer = require('rpc-websockets').Server;
const server = new WebSocketServer({ port: 8080 });
server.event('update');
setInterval(() => {
server.emit('update', { timestamp: new Date() });
}, 1000);
console.log('WebSocket server is running on ws://localhost:8080');
Listening to Events on Client
This code demonstrates how to create a WebSocket client that listens to events. The client connects to the server at ws://localhost:8080, subscribes to the 'update' event, and logs any received updates.
const WebSocketClient = require('rpc-websockets').Client;
const client = new WebSocketClient('ws://localhost:8080');
client.on('open', () => {
client.subscribe('update');
client.on('update', (data) => {
console.log('Update received:', data);
});
});
The ws package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server for Node.js. Unlike rpc-websockets, ws does not provide built-in support for JSON-RPC, but it offers a more flexible and lower-level API for WebSocket communication.
Socket.IO is a library that enables real-time, bidirectional, and event-based communication between web clients and servers. It provides higher-level abstractions compared to rpc-websockets, including automatic reconnection, multiplexing, and broadcasting, but does not natively support JSON-RPC.
rpc-websockets wraps ws library providing JSON RPC 2.0 support on top.
npm install rpc-websockets
var WebSocket = require('rpc-websockets').Client
var WebSocketServer = require('rpc-websockets').Server
// instantiate Server and start listening for requests
var server = new WebSocketServer({
port: 8080,
host: 'localhost',
rpc: {
root_path: '/rpc',
version: '1.0'
}
})
// register an RPC method
server.register('sum', function(params) {
return params[0] + params[1]
})
// create an event
server.event('feedUpdated')
// get events (getter method)
console.log(server.eventList)
// emit an event to subscribers
server.emit('feedUpdated')
// close the server
server.close()
// instantiate Client and connect to an RPC server
var ws = new WebSocket('ws://localhost:8080/rpc/1.0')
ws.on('open', function() {
// call an RPC method with parameters
ws.call('sum', [5, 3]).then(function(result) {
require('assert').equal(result, 8)
})
// send a notification to an RPC server
ws.notify('openedNewsModule')
// subscribe to receive an event
ws.subscribe('feedUpdated')
ws.on('feedUpdated', function() {
updateLogic()
})
// unsubscribe from an event
ws.unsubscribe('feedUpdated')
// close a websocket connection
ws.close()
})
var WebSocket = require('rpc-websockets').Client
var ws = new WebSocket('ws://localhost:8080/rpc/1.0')
Instantiate a WebSocket client.
Parameters:
address
{String}: The URL of the WebSocket server. Defaults to 'ws://localhost:8080/rpc/1.0'.options
{Object}: Client options that are also forwarded to ws
.
autoconnect
{Boolean}: Client autoconnect upon Client class instantiation. Defaults to true
.reconnect
{Boolean}: Whether client should reconnect automatically once the connection is down. Defaults to true
.reconnect_interval
{Number}: Time between adjacent reconnects. Defaults to 1000
.max_reconnects
{Number}: Maximum number of times the client should try to reconnect. Defaults to 5
.Calls a registered RPC method on server. Resolves once the response is ready. Throws if an RPC error was received.
Parameters:
method
{String}: An RPC method name to run on server-side.params
{Object|Array}: Optional parameter(s) to be sent along the request.Sends a JSON-RPC 2.0 notification to server.
Parameters:
method
{String}: An RPC method name to run on server-side.params
{Object|Array}: Optional parameter(s) to be sent along the request.Subscribes for a defined event.
Parameters:
event
{String}: Event name.Unsubscribes from a defined event.
Parameters:
event
{String}: Event name.Closes a WebSocket connection gracefully.
Parameters:
code
{Number}: Socket close code.data
{String}: Optional data to be sent to socket before closing.Emits when the connection is opened and ready for use.
Emits when a socket error is raised.
Emits when the connection is closed.
Emits a notification event with possible parameters a client has subscribed to once the server sends it.
Example:
ws.subscribe('feedUpdated')
ws.on('feedUpdated', handlerFunction)
var WebSocketServer = require('rpc-websockets').Server
var server = new WebSocketServer({
port: 8080,
host: 'localhost',
rpc: {
root_path: '/rpc',
version: '1.0'
}
})
Instantiate a WebSocket server.
Parameters:
options
{Object}: Server options that are also forwarded to ws
.
port
{Number}: Port number on which the server will listen for incoming requests.host
{String}: Address on which the server will listen for incoming requests.rpc
{Object}:
root_path
{String}: RPC server endpoint.version
{String}: RPC API version.Once the Server class is instantiated, you can use a ws
library's instance via server.wss object.
Registers an RPC method.
Parameters:
method
{String}: RPC method name.callback
{Function}: RPC function that will be fired with a possible parameter object once the method is called.Creates a new event that can be emitted to clients.
Parameters:
name
{String}: Name of the event.Emits a created event to clients.
Parameters:
name
{String}: Name of the event....params
: Parameters forwarded to clients.Lists all created events.
Creates a structured error that can be thrown in a .register callback.
Parameters:
code
{Number}: Indicates the error type that occurred.message
{String}: Provides a short description of the error.data
{String|Object}: Details containing additional information about the error.Closes the server and terminates all clients.
Emits when the server has started listening for requests.
Emits when a server error is raised.
FAQs
JSON-RPC 2.0 implementation over WebSockets for Node.js
The npm package rpc-websockets receives a total of 591,572 weekly downloads. As such, rpc-websockets popularity was classified as popular.
We found that rpc-websockets 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.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.