我想在NodeJS中为dgram
套接字实现超时。我四处寻找原生udp解决方案,例如socket.setTimeout
库中的net
。
以下是我的想法:
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();
此实现存在一些问题,例如,每次发送新数据报时,我都会绑定一个新的消息侦听器。我欢迎任何关于超时实现的建议
答案 0 :(得分:0)
怎么样
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()
}