Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
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.
The rpc-websockets library enables developers to easily implement their business logic that includes messaging between users, machines or any devices. It provides a possibility to send and receive JSON data through the WebSocket communication protocol in order to support two-way notification push, running RPC methods and firing any types of event signalling. Only clients can call RPC methods and not vice versa at the moment. Both frontend (HTML/JS-based) and backend (Node.js-based) development environments are supported.
rpc-websockets is built on Node.js and supports both LTS and Current versions.
Use the free OSS edition in order to implement and manage your own WebSocket server instances, or subscribe for our Pro plan and have us manage your instances and provide you with management of your methods, events and notifications on an easy-to-use Web Management portal.
Install our OSS library in your project:
npm install rpc-websockets
Write your source code using 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'
})
// register an RPC method
server.register('sum', function(params) {
return params[0] + params[1]
})
// ...and maybe a protected one also
server.register('account', function() {
return ['confi1', 'confi2']
}).protected()
// create an event
server.event('feedUpdated')
// get events
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')
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')
// login your client to be able to use protected methods
ws.login({'username': 'confi1', 'password':'foobar'}).then(function() {
ws.call('account').then(function(result) {
require('assert').equal(result, ['confi1', 'confi2'])
})
}).catch(function(error) {
console.log('auth failed')
})
// close a websocket connection
ws.close()
})
Please consult our API documentation for both WebSocket server and client JavaScript and TypeScript classes.
Features of the free open-source edition.
All library's open-source features are documented in our API documentation and can be used free of charge. You are free to implement your solutions based on provided methods in any way you are comfortable with, as long as you use our work along our very permissive license conditions.
In order to support your production-ready environments, we can provide you with additional features built on top of our free OSS edition along with the skill set to turn your business case or a Proof-of-Concept idea into reality.
Describe us your use case by contacting us and we will swiftly get back to you with a proposed solution that meets your needs.
We offer professional support for rpc-websockets and beyond. We have many years of expertise on building robust, scalable Node.js applications and can help you overcome issues and challenges preventing you to ship your great products. We excel in software architecture and implementation, being able to provide you with development, planning, consulting, training and customization services. Feel free to contact us so we can discuss how to help you finish your products!
rpc-websockets is being actively used in production by multiple companies in a variety of different use cases.
Become a sponsor and get your logo on project's README on GitHub with a link to your site. Feel free to contact us for the arrangement!
This library is licensed under LGPLv3. Please see LICENSE for licensing details.
FAQs
JSON-RPC 2.0 implementation over WebSockets for Node.js
The npm package rpc-websockets receives a total of 381,386 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.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.