2017-04-28 21:26:03 +00:00
|
|
|
# SocketPair
|
2017-04-28 11:29:30 -06:00
|
|
|
|
|
|
|
|
[](http://badge.fury.io/js/socket-pair)
|
|
|
|
|
|
2017-04-28 11:54:08 -06:00
|
|
|
A pair of coupled Unix sockets (or Windows pipes).
|
2017-04-28 11:29:30 -06:00
|
|
|
|
2018-05-29 16:37:31 -06:00
|
|
|
Similar to `stream-pair`, but with sockets with real fds and `.setTimeout()`.
|
|
|
|
|
Originally a workaround for <https://github.com/nodejs/node/issues/12716>,
|
|
|
|
|
but still has some use relevant cases, particularly when building proxies.
|
2017-04-28 11:29:30 -06:00
|
|
|
|
2017-07-27 20:57:49 -06:00
|
|
|
**Note**: This workaround is necessary in node v6.11.1, but not necessary in node v8.2.1.
|
|
|
|
|
I would assume it is also not necessary in later versions.
|
|
|
|
|
|
2017-04-28 11:29:30 -06:00
|
|
|
## Usage
|
|
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
|
var socketPair = require('socket-pair');
|
|
|
|
|
|
2017-04-28 12:24:39 -06:00
|
|
|
var socket = socketPair.create(function (err, other) {
|
2017-04-28 21:25:09 +00:00
|
|
|
// socket as in `client = new net.Socket(); client.connect(...);`
|
2017-04-28 12:24:39 -06:00
|
|
|
// other as in `server.on('connection', function (conn) { ... })`
|
2017-04-28 11:29:30 -06:00
|
|
|
|
2017-04-28 12:24:39 -06:00
|
|
|
socket.write('123');
|
|
|
|
|
other.on('data', function (chunk) {
|
2017-04-28 11:29:30 -06:00
|
|
|
console.log(chunk.toString('utf8'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
socketPair.closeAll();
|
|
|
|
|
});
|
|
|
|
|
```
|
|
|
|
|
|
2017-04-28 11:54:08 -06:00
|
|
|
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.
|
|
|
|
|
|
2017-04-28 11:29:30 -06:00
|
|
|
## API
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
socketPair.create(cb) // creates or reuses a socket server
|
|
|
|
|
socketPair.closeAll() // closes the server and all sockets
|
|
|
|
|
```
|