Skip to content

plantain-00/rpc-on-ws

Repository files navigation

rpc-on-ws

Dependency Status devDependency Status Build Status: Windows Github CI npm version Downloads gzip size type-coverage

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 * as WebSocket from "ws";

// browser(module):
// import WsRpc from "rpc-on-ws";

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

About

A lightweight RPC library on websocket connection.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published