rpc-on-ws
v5.1.0
Published
A lightweight RPC library on websocket connection.
Downloads
91
Readme
rpc-on-ws
A lightweight RPC library on websocket connection.
install
npm i rpc-on-ws
usage
server-side:
import * as WebSocket from "ws";
const wss = new WebSocket.Server({ port: 8000 });
wss.on("connection", ws => {
ws.on("message", data => {
const request: { id: number, response?: string, error?: string } = JSON.parse(data.toString());
setTimeout(() => { // mock heavy work
ws.send(JSON.stringify({
id: request.id,
response: "Hello world",
}));
}, 1000);
});
});
client-side:
import { Subject } from "rxjs";
// nodejs:
import WsRpc from "rpc-on-ws";
// import WsRpc from "rpc-on-ws/nodejs"; // ES syntax
import * as WebSocket from "ws";
// browser(module):
// import WsRpc from "rpc-on-ws";
// import WsRpc from "rpc-on-ws/browser"; // ES module
// browser(script tag):
// <script src="rpc-on-ws/rpc-on-ws.min.js"></script>
const subject = new Subject<{ id: number, response?: string, error?: string }>();
const wsRpc = new WsRpc(subject, message => message.id, message => message.error);
const ws = new WebSocket("ws://localhost:8000");
ws.onopen = () => {
ws.onmessage = data => {
subject.next(JSON.parse(data.data.toString()));
};
wsRpc.send(requestId => {
ws.send(JSON.stringify({ id: requestId, command: "abc" }));
}).then(response => {
console.log(`accept: ${response.id} ${response.response}`);
}, error => {
console.log(error);
});
};
optional, just generate request id
const requestId = wsRpc.generateRequestId();
change logs
// v5 rxjs@5 -> rxjs@6
// v4
import WsRpc from "rpc-on-ws/nodejs";
import WsRpc from "rpc-on-ws/browser";
// v3
import { WsRpc } from "rpc-on-ws";