连续发送UDP数据包时,Res.write不起作用

时间:2016-06-24 13:34:54

标签: html node.js udp

//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]

1 个答案:

答案 0 :(得分:1)

将代码放入自动代码格式化程序以使其可读后,我可以看到您正在执行此操作:

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

app.post()处理程序内部。这意味着每次调用post处理程序时,都会添加另一个client.on('message', ...)事件处理程序。因此,在第二次调用之后,你有两个事件处理程序,在它被称为第三次之后,你有三个等等。

因此,只要你有这些副本,每个人都会被调用,你会得到重复的动作。

您的选择是:

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