节点:在计时器上发送UDP数据包,无限循环

时间:2018-11-22 02:45:33

标签: node.js loops udp

我试图每隔几秒钟就以无限循环的方式每隔几秒钟从服务器发送一个数据包来ping客户端。

这是我正在运行的代码:

const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const clientPing = dgram.createSocket('udp4');

const pinging = true;

function ping() {
  clientPing.send("Hi Uno", 8888, 'XXX.XX.XX.XXX', (err) => {
    clientPing.close();
  });
}

function sleep(time, callback) {
    var stop = new Date().getTime();
    while(new Date().getTime() < stop + time) {
        ;
    }
    callback();
}

function loop() {
  while(pinging == true) {
    sleep(3000, function() {
      ping();
      console.log('ping');
    });
  }
}

loop();

奇怪的是,控制台在给定间隔记录了ping字符串,但该数据包从未发送过,也从未到达过我的客户端。但是,当我只在循环外运行ping();时,数据包就会到达客户端。

Udp在发送数据包后不等待响应,而不必等待响应。我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

正如@tkausl所说,您正在阻止事件循环。不要使用该sleep()函数。尝试这样的事情:

function loop() {
  if (!pinging) {
    return;
  }
  ping();
  console.log('ping');
  setTimeout(loop, 3000);
}

loop();

答案 1 :(得分:0)

所以我终于知道它可以通过以下方式正常工作:

import Decisions
import Characters
import Locations

def main():
    Player = Characters.Character([], 100)
    Loc = Locations.Location(0, 0)

answer = Decisions.choice_yes_no.choice_yes_no("You woke up, discovering 
that somehow you were in the middle of a dark dungeon. A sword lies to the 
left of you, pick it up? (Yes/No) ")
if answer == True:
    print("You picked up the sword.")
    Player.add_item("Sword")

elif answer == False:
    print("You chose not to pick up the sword.")

answer_2 = Decisions.choice_direction.choice_direction("You stood up, 
patting the dust off your clothes, you looked around. The room was dark and 
you view was limited to a few meters. Where do you go? 
\n(Left/Right/Forward/Back)   ")
if answer == "forward":
    Loc.y = Loc.y + 1
elif answer == "back":
    Loc.move_back()
elif answer == "left":
    Loc.move_left()
elif answer == "right":
    Loc.move_right()

print(Loc.x)
print(Loc.y)

main()  #REMOVE BEFORE USING#

因此,现在运行Pi的Pi每5秒钟成功ping通我的arduino客户端,然后arduino响应温度和湿度数据,然后Pi服务器将其捕获并将其推送到mongo。