Last active
August 29, 2015 14:26
-
-
Save mattpodwysocki/af6ffa8279c6847f00c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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