我正在编写一个node.js应用程序,并且从net.Server获得了net.Socket。我正在编写一个名为RpcSocket的类:
class RpcSocket {
constructor(socket) {
this.idToAssign = 1;
this.handlers = {};
this.socket = socket;
this.socket.on('error', e => log.error('socket', e));
const incoming = JSONStream.parse();
incoming.on('data', object => {
const parsedObject = jsonrpc.parseObject(object);
switch (parsedObject.type) {
case 'request':
const response = this.handlers[parsedObject.payload.method](parsedObject.payload.id); // TODO check if it exists
socket.write(JSON.stringify(response));
break;
case 'success':
console.log('success', parsedObject.payload.result); // TODO do something useful, use the ID. Probably need to track IDs
}
});
incoming.on('error', e => log.error('incoming', e));
socket.pipe(incoming);
}
setHandler(method, func) {
this.handlers[method] = func;
}
request(method, params) {
this.socket.write(JSON.stringify(jsonrpc.request(this.idToAssign++, method, params)));
}}
当前,此类仅接收套接字并将其分配为实例属性。我想让RpcSocket扩展Socket。我遇到的问题是我不知道如何将实例化的Socket转换为RpcSocket。