@cloudpss/ubrpc
TypeScript icon, indicating that this package has built-in type declarations

0.5.30 • Public • Published

@cloudpss/ubrpc

Rpc server/client build on websocket and ubjson.

Introduction

本模块是基于 websocket 和 ubjson 的 rpc 服务端/客户端模块。使用 websocket 作为底层通信协议,使用 ubjson 作为数据序列化协议。在建立连接后,支持通过 websocket 实现双向调用。

Usage

作为 WebSocket 服务端

import { WebSocketServer } from 'ws';
import { RpcServer } from '@cloudpss/ubrpc';

const rpc = new RpcServer(
  {
    hello(name) {
      return `Hello, ${name}`;
    },
  },
  (meta) => {
    // 校验客户端信息,拒绝连接时抛出异常
    // 返回服务端信息供客户端验证
    return {};
  },
);

const server = new WebSocketServer({
  host: 'localhost',
  port: 8090,
  path: '/',
});
server.on('connection', async (socket) => {
  try {
    await rpc.connect(socket);
  } catch (ex) {
    console.log(ex);
  }
});

作为 WebSocket 客户端

import { RpcClientSocket } from '@cloudpss/ubrpc';

const rpc = new RpcClientSocket('ws://localhost:8090');
const result = await rpc.call('hello', 'world');
console.log(result);

Readme

Keywords

Package Sidebar

Install

npm i @cloudpss/ubrpc

Weekly Downloads

63

Version

0.5.30

License

MIT

Unpacked Size

99.1 kB

Total Files

56

Last publish

Collaborators

  • opportunity