Reputation: 500
I'm working on an application and I want the user to be able to change the ip and port of a udp socket that is listening already in localhost:7777.
ipcMain.on('ip', function(e,data) {
port = data["port"];
console.log(data["port"]);
adress = data["adress"];
server.close();
//??
//const address = server.address();
//console.log(`server listening ${address.address}:${address.port}`);
});
var port = 7777;
var adress = "localhost";
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
var infoMap = processMsgCyrano1(msg);
if (infoMap["Com"] === "INFO") {
console.log(`Left Fencer: ${infoMap["LeftName"]}`);
console.log(`Right Fencer: ${infoMap["RightName"]}`);
HTMLupdate(infoMap);
}
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(port, adress);
I'm using electron, and the info is received by ipcMain.on correctly. The problem is that once I close the previous socket, I don't know how to open it again (if this is possible) with different IP and port adress. Is there any way to change it without creating another socket? And if not, is there any way to save the previous configuration and don't be redundant?
Upvotes: 0
Views: 98
Reputation: 6924
How about using a builder function with some delegations?
const dgram = require('dgram')
function socketBuilder(address, port, events)
{
const server = dgram.createSocket('udp4')
if (!events) events = {}
if (events.error instanceof Function) server.on('error ', events.error)
if (events.message instanceof Function) server.on('message', events.message)
if (events.listen instanceof Function) server.on('listening', events.listen)
server.bind(port, address)
return server
}
Now you can simply use it as so:
const server = socketBuilder('localhost', '7777',
{
message: (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
var infoMap = processMsgCyrano1(msg);
if (infoMap["Com"] === "INFO") {
console.log(`Left Fencer: ${infoMap["LeftName"]}`);
console.log(`Right Fencer: ${infoMap["RightName"]}`);
HTMLupdate(infoMap);
}
},
error: (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
},
listen: () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
}
})
And also re-use it pretty much whenever you need. What do you think?
Upvotes: 1