基于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  
    }  
});

 

上一篇:Solana主网使用自定义的RPC进行转账-sol转账代码


下一篇:区块链媒体推广的8个成功案例解析-华媒舍