36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
|
const DHT = require("@hyperswarm/dht");
|
||
|
const net = require("net");
|
||
|
const pump = require("pump");
|
||
|
const node = new DHT({});
|
||
|
module.exports = () => {
|
||
|
return {
|
||
|
serve: (keyPair, host, port) => {
|
||
|
const server = node.createServer();
|
||
|
server.on("connection", function (servsock) {
|
||
|
const socket = net.connect(port, host);
|
||
|
socket.on('serve error', console.error);
|
||
|
let open = { servsock: true, remote: true };
|
||
|
servsock.on('data', (d) => { socket.write(d) });
|
||
|
socket.on('data', (d) => { servsock.write(d) });
|
||
|
|
||
|
const remoteend = () => {
|
||
|
if (open.remote) socket.end();
|
||
|
open.remote = false;
|
||
|
}
|
||
|
const servsockend = () => {
|
||
|
if (open.servsock) servsock.end();
|
||
|
open.servsock = false;
|
||
|
}
|
||
|
servsock.on('error', remoteend)
|
||
|
servsock.on('finish', remoteend)
|
||
|
servsock.on('end', remoteend)
|
||
|
socket.on('finish', servsockend)
|
||
|
socket.on('error', servsockend)
|
||
|
socket.on('end', servsockend)
|
||
|
});
|
||
|
server.listen(keyPair);
|
||
|
return keyPair.publicKey;
|
||
|
}
|
||
|
};
|
||
|
};
|