Skip to content

Instantly share code, notes, and snippets.

@bmatusiak
Last active August 30, 2023 11:19
Show Gist options
  • Save bmatusiak/bd8a2500d1c565b297a369d8ecc867ac to your computer and use it in GitHub Desktop.
Save bmatusiak/bd8a2500d1c565b297a369d8ecc867ac to your computer and use it in GitHub Desktop.
gun uds Unix_domain_socket
const net = require('net');
const path = require('path');
const fs = require('fs');
var listen_path = path.join(process.cwd(), 'gun_sockets');
if (!fs.existsSync(listen_path)) {
fs.mkdirSync(listen_path);
}
listen_path = path.join(listen_path, 'gun.socket');
var isWin = (process.platform.indexOf("win") > -1);
if (isWin)
listen_path = path.join('\\\\?\\pipe', listen_path);
if (process.env.GUN_SOCKET)
listen_path = process.env.GUN_SOCKET
var Gun = require("gun");
module.exports = {
server: function (gun) {
var server = net.createServer((socket) => {
if (!socket.peer) {
socket.peer = new GunSocketWire(gun, socket);
socket.on("end", () => socket.peer.ondisconnect());
}
socket.peer.onconnect();
console.log('uds client connected');
// socket.on('data', (data) => {
// console.log(data.toString());
// });
// socket.on('end', () => {
// console.log('client disc?onnected');
// });
}).on('error', (err) => {
console.warn(err);
// throw err;
});
if (!isWin && fs.existsSync(listen_path))
fs.unlink(listen_path)
server.listen(listen_path, () => {
console.log('opened server on', server.address());
});
},
client: function (gun) {
var client = net.createConnection(listen_path, () => {
});
var peer = new GunSocketWire(gun, client);
// client.on('data', (data) => {
// console.log(data.toString());
// });
client.on('connect', () => {
peer.onconnect()
// console.log('connected to server!');
});
var t;
client.on('end', () => {
peer.ondisconnect()
// console.log('disconnected from server');
if (!t) t = setTimeout(() => { t = false; client.connect(listen_path) }, 1000);
});
client.on('error', (e) => {
// console.log('error',e);
if (e.code == "ENOENT")
if (!t) t = setTimeout(() => { t = false; client.connect(listen_path) }, 1000);
});
}
}
class GunSocketWire {
constructor(gun, socket) {
var opt = gun._.opt;
this.socket = socket;
this.mesh = opt.mesh = opt.mesh || Gun.Mesh(gun);
this.peer = { wire: this };
this._connected = false;
socket.on("data", (data) => {
this.onmessage(data.toString())
})
}
onmessage(msg) {
if (this._connected)
this.mesh.hear(msg.data || msg, this.peer);
}
onconnect() {
this.mesh.hi(this.peer);
this._connected = true;
}
ondisconnect() {
this.mesh.bye(this.peer);
this._connected = false;
}
send(msg) {
this.socket.write(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment