01-basic-ipc.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. /**
  2. * 示例 1: 基础 IPC —— 通过内存 Queue 演示完整的 RPC 调用
  3. *
  4. * 演示了最核心的流程:
  5. * 1. 创建内存传输对 (QueueProtocol)
  6. * 2. 在服务端注册一个 channel
  7. * 3. 客户端获取 channel 并调用方法 / 监听事件
  8. *
  9. * 数据流:
  10. * client.call('add', [1, 2])
  11. * ↓ serialize → send
  12. * [protocol A] ──buffer──→ [protocol B]
  13. * ↓ deserialize → dispatch
  14. * channel.call(ctx, 'add', [1, 2])
  15. * ↓ return 3
  16. * [protocol B] ──buffer──→ [protocol A]
  17. * ↓ deserialize → resolve promise
  18. * result = 3
  19. */
  20. import {
  21. Emitter,
  22. Event,
  23. IServerChannel,
  24. ChannelServer,
  25. ChannelClient,
  26. createQueuePair,
  27. } from "../src/index.js";
  28. // ============================================================================
  29. // Step 1: 定义一个 service(普通 TypeScript 对象)
  30. // ============================================================================
  31. class CalculatorService {
  32. private readonly _onDidCompute = new Emitter<{ op: string; result: number }>();
  33. readonly onDidCompute = this._onDidCompute.event;
  34. add(a: number, b: number): number {
  35. const result = a + b;
  36. this._onDidCompute.fire({ op: `${a} + ${b}`, result });
  37. return result;
  38. }
  39. multiply(a: number, b: number): number {
  40. const result = a * b;
  41. this._onDidCompute.fire({ op: `${a} * ${b}`, result });
  42. return result;
  43. }
  44. async divide(a: number, b: number): Promise<number> {
  45. if (b === 0) {
  46. throw new Error("Division by zero");
  47. }
  48. const result = a / b;
  49. this._onDidCompute.fire({ op: `${a} / ${b}`, result });
  50. return result;
  51. }
  52. }
  53. // ============================================================================
  54. // Step 2: 手写 IServerChannel(后面的例子会用 ProxyChannel 自动化)
  55. // ============================================================================
  56. class CalculatorChannel implements IServerChannel {
  57. constructor(private service: CalculatorService) {}
  58. call(_ctx: string, command: string, arg?: any): Promise<any> {
  59. switch (command) {
  60. case "add":
  61. return Promise.resolve(this.service.add(arg[0], arg[1]));
  62. case "multiply":
  63. return Promise.resolve(this.service.multiply(arg[0], arg[1]));
  64. case "divide":
  65. return this.service.divide(arg[0], arg[1]);
  66. default:
  67. throw new Error(`Unknown command: ${command}`);
  68. }
  69. }
  70. listen(_ctx: string, event: string): Event<any> {
  71. switch (event) {
  72. case "onDidCompute":
  73. return this.service.onDidCompute;
  74. default:
  75. throw new Error(`Unknown event: ${event}`);
  76. }
  77. }
  78. }
  79. // ============================================================================
  80. // Step 3: 建立连接并进行 RPC
  81. // ============================================================================
  82. async function main() {
  83. // 创建内存传输对
  84. const [protocolA, protocolB] = createQueuePair();
  85. // 服务端:在 protocolB 上注册 channel
  86. const service = new CalculatorService();
  87. const server = new ChannelServer(protocolB, "server-ctx");
  88. server.registerChannel("calculator", new CalculatorChannel(service));
  89. // 客户端:通过 protocolA 获取 channel
  90. const client = new ChannelClient(protocolA);
  91. // 等待初始化完成
  92. await Event.toPromise(client.onDidInitialize);
  93. const calculator = client.getChannel("calculator");
  94. // 订阅事件
  95. const disposable = calculator.listen<{ op: string; result: number }>("onDidCompute")((e) => {
  96. console.log(` [event] ${e.op} = ${e.result}`);
  97. });
  98. // 调用方法
  99. console.log("--- Basic IPC Demo ---");
  100. const sum = await calculator.call<number>("add", [10, 20]);
  101. console.log(`add(10, 20) = ${sum}`);
  102. const product = await calculator.call<number>("multiply", [6, 7]);
  103. console.log(`multiply(6, 7) = ${product}`);
  104. const quotient = await calculator.call<number>("divide", [100, 3]);
  105. console.log(`divide(100, 3) = ${quotient}`);
  106. // 测试错误传播
  107. try {
  108. await calculator.call("divide", [1, 0]);
  109. } catch (err: any) {
  110. console.log(`divide(1, 0) → Error: ${err.message}`);
  111. }
  112. // 清理
  113. disposable.dispose();
  114. client.dispose();
  115. server.dispose();
  116. console.log("\nDone!");
  117. }
  118. main().catch(console.error);