createServer((socket) => {
const connection = new ServerConnection(socket);
const protocol = new ServerProtocol();
const handle = new ServerHandle((ctx) => {
console.log('Server got', ctx.request);
ctx.response = { pong: 'pong' };
});
const ctx = { connection, protocol, handle } as Context;
(async () => {
/**
* 内部执行
* const buf = await ctx.connection.read();
* ctx.request = ctx.protocol.decode(buf);
* ...
* const buf = ctx.protocol.encode(ctx.response);
* await ctx.connection.write(buf);
*/
await handle.execute(ctx);
})();
}).listen(3000);
(async () => {
const socket = connect({ port: 3000 });
const connection = new ClientConnection(socket);
const protocol = new ClientProtocol();
const handle = new ClientHandle();
const ctx = { connection, protocol, handle } as Context;
ctx.request = { ping: 'ping' };
/**
* 内部执行
* const buf = ctx.protocol.encode(ctx.request);
* await ctx.connection.write(buf);
* ...
* const buf = await ctx.connection.read();
* ctx.response = ctx.protocol.decode(buf);
*/
await handle.execute(ctx);
console.log('Client got', ctx.response);
})();
讲rpc 很不错的一篇文章https://mp.weixin.qq.com/s/Ky6SoWJv85orqYioihTRqg