Res.write is not working when continuously sending

2019-09-02 08:28发布

问题:

//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');

I have two button, one button sends the UDP packet once, while a continuous button sends the same UDP packets every 10 seconds. However, when this button is pressed, res.write is repeating the entire output again. Look at the attached pic to see output[![enter image description here][1]][1]

回答1:

After putting your code into an auto-code-formatter to make it readable, I can see that you are doing this:

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

inside of your app.post() handler. That means that every time your post handler is called, you add yet another client.on('message', ...) event handler. So, after it's called the 2nd time, you have two event handlers, after it's called the 3rd time, you have three and so on.

So, as soon as you have these duplicate, each will get called and you will get duplicate actions applied.

Your choices are to either:

  1. Use .once() for the event handler so it is automatically removed after it fires.
  2. Remove it manually after it fires or when you are done with it.
  3. Add it once outside your app.post() handler so you never add duplicates.
  4. Restructure the way your code works so it doesn't have this type of issue. For example, you have two different handlers for the same incoming message. This is a sign of very stateful code which is more complex to write properly. A better design that isn't stateful in that way would be simpler.


标签: html node.js udp