q-socket v0.0.4
Q-Socket
Q-Socket makes using Node sockets under q and q-connection easier by providing the following functions:
listen(args, onconnected)
Returns a promise object, to be fulfilled when underlying server
port gets gracefully closed; or rejected, if the server port generates
an error or if unsufficient arguments were given to listen.
onconnected callback will be invoked with accepted socket object every
time a connection is made to the underlying server port.
Arguments
args is an object, specifying the following properties:
TCP sockets
args.portnumerical port numberargs.hostoptional host, defaults to localhostargs.backlogoptional depth of accept queue
UNIX sockets
args.pathUNIX socket path string
or
args.handlethehandleobject can be set to either a server or socket (anything with an underlying _handle member), or a {fd: } object
common properties
args.optionsoptional object, set up as per net.createServer
onconnected Function object
Example
Below is a simple 'time' server, which also happens to demonstrate a use of
portify function, further described below.
var qConnection = require('q-connection'),
Qs = require('q-socket'),
util = require('util'),
service = function() { return Date.now() };
function raddr(socket) {
return (socket && socket.remoteAddress && socket.remotePort &&
util.format('%s:%d', socket.remoteAddress, socket.remotePort))
|| '';
}
Qs.listen({port: 9999, host: "127.0.0.1"}, function(socket) {
var port = Qs.portify(socket),
peer = raddr(socket);
console.log('Accepted connection:', peer);
qConnection(port, service);
socket.on('close', function() {
console.log('Client disconnected:', peer);
});
}).done(function() {
console.log('Done.');
});connect(options)
Returns a promise object, which is resolved with a socket on connection or rejected with error.
Arguments
options object is a single argument to connect(options) function, which may specify the following properties:
TCP sockets
options.portrequired port numberoptions.hostoptional host. If not specified, uses local host by default.options.localAddressoptional local interface for the connection.
UNIX sockets
options.pathUNIX socket path string
common options
allowHalfOpenboolean argument, detailed in net.connect
Example
This is a client to the simple 'time' server above.
var qConnection = require('q-connection'),
Qs = require('q-socket');
Qs.connect({host: '127.0.0.1', port: 9999}).then(function(socket) {
var service = qConnection(Qs.portify(socket));
service.fcall().done(function(data) {
console.log('Response:', new Date(data));
socket.end();
});
});portify(socket)
Makes a q-connection compatible port out of given socket object and returns it.
Example
See above client and server samples for examples of portify use.