better bookkeeping

This commit is contained in:
AJ ONeal 2017-04-28 11:54:08 -06:00
parent 59412361e1
commit 00fd61add0
2 changed files with 36 additions and 17 deletions

View File

@ -2,7 +2,7 @@
[![NPM version](https://badge.fury.io/js/socket-pair.svg)](http://badge.fury.io/js/socket-pair)
A pair of coupled sockets.
A pair of coupled Unix sockets (or Windows pipes).
Similar to `stream-pair`, but with sockets with real fds. A workaround for <https://github.com/nodejs/node/issues/12716>.
@ -11,9 +11,9 @@ Similar to `stream-pair`, but with sockets with real fds. A workaround for <http
```javascript
var socketPair = require('socket-pair');
socketPair.create(function (pair) {
var a = pair.client;
var b = pair.connection;
socketPair.create(function (err, pair) {
var a = pair.client; // as in `client = net.connect()`
var b = pair.connection; // as in `server.on('connection', function (conn) { ... })`
a.write('123');
b.on('data', function (chunk) {
@ -24,6 +24,10 @@ socketPair.create(function (pair) {
});
```
I named them `client` and `connection`, but their names really have no meaning.
You can call them `a` and `b` or `other` and `one` or `red` and `blue`. It makes no difference.
## API
```

View File

@ -4,7 +4,7 @@ var server;
var listening = false;
var sock;
function createServer(prefix) {
function createServer(cb, prefix) {
var os = require('os');
var net = require('net');
var path = require('path');
@ -18,29 +18,44 @@ function createServer(prefix) {
}
server = net.createServer();
function onServerError(err) {
cb(err);
}
server.once('error', onServerError);
server.once('listening', function () {
listening = true;
server.removeListener('error', onServerError);
});
}
exports.create = function create(cb, prefix) {
var net = require('net');
var writer;
var client;
function createConnection() {
function onClientError(err) {
cb(err);
}
client = net.connect(sock, function () {
client.removeListener('error', onClientError);
});
client.once('error', onClientError);
}
// This server listens on a Unix socket or Windows pipe at 'sock'
if (!server) {
createServer(prefix);
}
if (!listening) {
server.listen(sock, function () {
writer = net.connect(sock);
listening = true;
});
createServer(cb, prefix);
}
server.once('connection', function each(reader) {
cb({ reader: reader, writer: writer });
server.once('connection', function onEach(connection) {
cb(null, { client: client, connection: connection });
});
if (listening) {
writer = net.connect(sock);
if (!listening) {
server.listen(sock, createConnection);
}
else {
createConnection();
}
};