Res.write 连续发送 UDP 数据包时不工作

Res.write is not working when continuously sending UDP packet

//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express(), ejs = require('ejs');
var plotly = require('plotly')("Patidar", "ku0sisuxfm")


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));

//Reading in the html file for input page
app.get('/', function(req, res){
    var html = fs.readFileSync('index2.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

//reading in html file for output page
app.get('/output', function(req, res){
    var html = fs.readFileSync('index4.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

//Recieving UDP message

app.post('/output', function(req, res){
var once= req.body.submit;

if (once == "Once") {
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');

//Sends packets to TFTP

client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
        if (err) throw err;
  });

//Recieving message back and printing it out to webpage
    client.on('message', function (message) {
 fs.readFile('index3.html', 'utf-8', function(err, content) {
      if (err) {
        res.end('error occurred');
        return;
      }
      var temp = message.toString();  //here you assign temp variable with needed value

      var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT});  //get redered HTML code
        res.end(renderedHtml);
      //var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
      //var layout = {fileopt : "overwrite", filename : "simple-node-example"};
      //plotly.plot(data, layout, function (err, msg) {
        //if (err) return console.log(err);
        //console.log(msg);
      //});
    });
  });
}


if (once == "continuous") {
var timesRun = 0;
var requestLoop = setInterval(function(){
  timesRun += 1;
   if(timesRun === 5){
       clearInterval(requestLoop);
   }
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');

//Sends packets to TFTP

client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
        if (err) throw err;
  });

//Recieving message back and printing it out to webpage

client.on('message', function (message) {
  fs.readFile('index3.html', 'utf-8', function(err, content) {
      if (err) {
        res.end('error occurred');
        return;
      }
      var temp = message.toString();  //here you assign temp variable with needed value

      var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT});  //get redered HTML code
      res.write(renderedHtml);

      //var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
      //var layout = {fileopt : "overwrite", filename : "simple-node-example"};

      //plotly.plot(data, layout, function (err, msg) {
        //if (err) return console.log(err);
        //console.log(msg);
      //});
});
});
}, 10000);
}
});



//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');

我有两个按钮,一个按钮发送一次UDP数据包,而一个连续按钮每10秒发送一次相同的UDP数据包。但是,按下此按钮时,res.write 将再次重复整个输出。查看所附图片以查看输出[![在此处输入图片描述][1]][1]

将您的代码放入自动代码格式化程序以使其可读后,我可以看到您正在这样做:

client.on('message', function (message) { ...

在您的 app.post() 处理程序中。这意味着每次调用 post 处理程序时,您都会添加另一个 client.on('message', ...) 事件处理程序。因此,在第二次调用后,您有两个事件处理程序,在第三次调用后,您有三个,依此类推。

因此,一旦您拥有这些副本,每个副本都会被调用,您将获得重复的操作。

您的选择是:

  1. .once() 用作事件处理程序,以便它在触发后自动删除。
  2. 在触发后或完成后手动将其删除。
  3. 在您的 app.post() 处理程序之外添加一次,这样您就永远不会添加重复项。
  4. 重构代码的工作方式,使其不存在此类问题。例如,对于同一传入消息,您有两个不同的处理程序。这是非常有状态代码的标志,正确编写起来更复杂。以这种方式没有状态的更好的设计会更简单。