基于JavaScript的简单RPC原理演示

创建RPC服务器

const WebSocket = require('ws');  
  
class RPCServer {  
    constructor(port) {  
        this.wss = new WebSocket.Server({ port });  
        this.methods = {};  
        this.wss.on('connection', (ws) => this.handleConnection(ws));  
    }  
  
    registerMethod(name, callback) {  
        this.methods[name] = callback;  
    }  
  
    handleConnection(ws) {  
        ws.on('message', (data) => {  
            const request = JSON.parse(data);  
            const methodName = request.method;  
            if (this.methods[methodName]) {  
                this.methods[methodName](request.params, (result) => {  
                    ws.send(JSON.stringify({ id: request.id, result }));  
                });  
            } else {  
                ws.send(JSON.stringify({ id: request.id, error: 'Method not found' }));  
            }  
        });  
    }  
}  
  
// 使用示例:  
const rpcServer = new RPCServer(8080);  
  
rpcServer.registerMethod('add', (params, callback) => {  
    const a = params.a;  
    const b = params.b;  
    callback(a + b);  
});

创建RPC客户端

const WebSocket = require('ws');  
  
class RPCClient {  
    constructor(url) {  
        this.ws = new WebSocket(url);  
        this.idCounter = 0;  
        this.callbacks = {};  
        this.ws.on('open', () => console.log('Connected to RPC server'));  
        this.ws.on('message', (data) => this.handleMessage(data));  
    }  
  
    callMethod(methodName, params, callback) {  
        const id = this.idCounter++;  
        this.callbacks[id] = callback;  
        const request = { id, method: methodName, params };  
        this.ws.send(JSON.stringify(request));  
    }  
  
    handleMessage(data) {  
        const response = JSON.parse(data);  
        const callback = this.callbacks[response.id];  
        if (callback) {  
            if (response.error) {  
                callback(new Error(response.error));  
            } else {  
                callback(null, response.result);  
            }  
            delete this.callbacks[response.id];  
        }  
    }  
}  
  
// 使用示例:  
const rpcClient = new RPCClient('ws://localhost:8080');  
rpcClient.callMethod('add', { a: 5, b: 3 }, (err, result) => {  
    if (err) {  
        console.error('Error:', err);  
    } else {  
        console.log('Result:', result); // 应输出 8  
    }  
});

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值