connection
connection socket wrapper
Usage
Client Socket
const net = require('net');
const awaitFirst = require('await-first');
const Connection = require('connection');
const Decoder = require('sofa-bolt-node/lib/decoder');
const Encoder = require('sofa-bolt-node/lib/encoder');
const protocol = {
name: 'Rpc',
encoder: opts => new Encoder(opts),
decoder: opts => new Decoder(opts),
};
async function createConnection(hostname, port) {
const socket = net.connect(port, hostname);
await awaitFirst(socket, [ 'connect', 'error' ]);
return new Connection({
logger: console,
socket,
protocol,
});
}
const conn = await createConnection('127.0.0.1', 12200);
conn.writeRequest({
targetAppName: 'foo',
args: [ 'peter' ],
serverSignature: 'com.alipay.sofa.rpc.quickstart.HelloService:1.0',
methodName: 'sayHello',
methodArgSigs: [ 'java.lang.String' ],
requestProps: null,
});
Server Socket
const Connection = require('connection');
const server = net.createServer();
server.listen(port);
server.on('connection', sock => {
const conn = new Connection({
logger: console,
socket: sock,
protocol,
});
conn.on('request', req => {
conn.writeResponse(req, {
error: null,
appResponse: 'hello, peter',
responseProps: null,
});
});
});
More example
API
- oneway() - one way call
- async writeRequest(req) - write request and wait response
- async writeResponse(req, res) - write response
- async close() - wait all pending request done and destroy the socket
- async forceClose() - abort all pending request and destroy the socket
- get protocolOptions() - encoder/decoder constructor options, can be overwrite when custom protocol
Protocol implement
interface Request {
oneway: boolean,
timeout: number,
packetType: string,
}
interface Response {
packetId: number,
}
interface Encoder extends Transform {
writeRequest(id: number, req: object, cb);
writeResponse(req: object, res: object, cb);
}
interface Decoder extends Writable {
}
interface Protocol {
name: string;
encode(options: any): Encoder;
decode(options: any): Decoder;
}
License
MIT
Contributors
This project follows the git-contributor spec, auto updated at Wed Jun 19 2024 17:29:25 GMT+0800
.