Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/af6ffa8279c6847f00c6 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/af6ffa8279c6847f00c6 to your computer and use it in GitHub Desktop.
'use strict';
var multiplex = require('multiplex');
function noop () { }
function muxServerBridge(tcpEndpointServerPort) {
var serverPlex = multiplex({}, function(stream, id) {
var clientSocket = net.createConnection({port: tcpEndpointServerPort});
stream.pipe(clientSocket).pipe(stream);
});
var server = net.createServer(function(incomingClientSocket) {
incomingClientSocket.pipe(serverPlex).pipe(incomingClientSocket);
});
return server;
}
function muxClientBridge(localP2PTcpServerPort, cleanUpCallBack) {
cleanUpCallBack || (cleanUpCallBack = noop)
var clientPlex = multiplex();
var clientSocket = net.createConnection({port: localP2PTcpServerPort});
var server = net.createServer(function(incomingClientSocket) {
var clientStream = clientPlex.createStream();
incomingClientSocket.pipe(clientStream).pipe(incomingClientSocket);
});
cleanUpSocket(clientSocket, function() {
clientPlex.destroy();
var err = null;
try {
server.close();
} catch(e) {
e = err;
}
cleanUpCallBack(err);
});
clientPlex.pipe(clientSocket).pipe(clientPlex);
return server;
}
function cleanUpSocket(socket, cleanUpCallBack) {
var isClosed = false;
socket.on('end', function() {
cleanUpCallBack();
isClosed = true;
});
socket.on('error', function(err) {
cleanUpCallBack(err);
isClosed = true;
});
socket.on('close', function() {
if (!isClosed) {
cleanUpCallBack();
isClosed = true;
}
});
}
module.exports = {
muxServerBridge: muxServerBridge,
muxClientBridge: muxClientBridge
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment