# @cloudpss/ubrpc

Rpc server/client build on websocket and ubjson.

## Introduction

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

## Usage

### 作为 WebSocket 服务端

```ts
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 客户端

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

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