我想为 dgram
实现超时NodeJS 中的套接字。我四处寻找像 socket.setTimeout
这样的原生 udp 解决方案。在 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();
这个实现存在一些问题,例如,每次我发送一个新的数据报时,我都会绑定(bind)一个新的消息监听器。我欢迎任何关于超时实现的建议
最佳答案
这个怎么样
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()
}
关于javascript - nodejs 上 dgram 套接字的超时实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48467563/