I want to implement a timeout for dgram sockets in NodeJS. I looked around for a native udp solution like the socket.setTimeout in net library.
Here is what I am thinking:
const Dgram = require("dgram");
const udpSocket = Dgram.createSocket("udp4");
const promiseTimeout = (promise, ms=5000) => {
// Create a promise that rejects in <ms> milliseconds
const timeoutPromise = new Promise(resolve => {
const timeout = setTimeout(() => {
clearTimeout(timeout);
resolve(false);
}, ms);
});
// Returns a race between timeout and the passed in promise
return Promise.race([
promise,
timeout
]);
};
const sendUdpMessage = (message, host, port) => {
return new Promise(resolve => {
udpSocket.send(message, 0, message.length, port, host);
udpSocket.on("message", (incomingMessage, rinfo) => {
console.log("I got message on udp", incomingMessage);
resolve(true);
});
});
};
const test = async () => {
const didUdpGotResponse = await promiseTimeout(sendUdpMessage("hello", "localhost", 5555));
console.log(didUdpGotResponse);
}
test();
There are some issues with this implementation, for example I am binding a new on message listener, every time I send a new datagram. I welcome any suggestions for a timeout implementation
how about this
const dgram = require('dgram')
const client = dgram.createSocket('udp4')
let timer = null
client.on('error', (err) => {
console.log(`client err:\n${ err.stack }`)
client.close()
})
client.on('message', msg => {
clearTimeout(timer)
console.log('I got message on udp')
})
ping()
function isTimeout () {
timer = setTimeout(() => {
console.log('udp request timeout')
}, 1000)
}
function ping () {
client.send('hello', 8080, 'localhost')
isTimeout()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With