# @cloudpss/ubrpc

Rpc server/client build on websocket and ubjson, supports bidirectional calls, async iterators and observables.

## Example

### 作为 WebSocket 服务端

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

const rpc = new RpcServer(
  {
    hello(name) {
      return `Hello, ${name}`;
    },
  },
  (meta) => {
    // 校验客户端信息，拒绝连接时抛出异常
    if (!meta.token) throw new Error('Unauthorized');
    // 返回服务端信息供客户端验证
    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', { token: 'my-token' });
const result = await rpc.call('hello', 'world');
console.log(result);
rpc.destroy();
```
