繁体   English   中英

nodejs 上 dgram 套接字的超时实现

[英]Timeouts implementation for dgram sockets on nodejs

我想在 NodeJS 中为dgram套接字实现超时。 我四处寻找像net库中的socket.setTimeout这样的原生 udp 解决方案。

这是我的想法:

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();

此实现存在一些问题,例如,每次发送新数据报时,我都会绑定一个新的消息侦听器。 我欢迎任何关于超时实施的建议

这个怎么样

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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM