rpc-on-ws
TypeScript icon, indicating that this package has built-in type declarations

5.1.0 • Public • Published

rpc-on-ws

Dependency Status devDependency Status Build Status: Linux Build Status: Windows npm version Downloads gzip size

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";

Readme

Keywords

none

Package Sidebar

Install

npm i rpc-on-ws

Weekly Downloads

0

Version

5.1.0

License

MIT

Unpacked Size

20.7 kB

Total Files

8

Last publish

Collaborators

  • plantain_00