连续发送UDP数据包时,Res.write不起作用 [英] Res.write is not working when continuously sending UDP packet

查看:112
本文介绍了连续发送UDP数据包时,Res.write不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //发送UDP消息到TFTP服务器
// dgram modeule创建UDP套接字
var express = require('express'),fs = require 'fs'),path = require('path'),util = require('util'),dgram = require('dgram'),client = dgram.createSocket('udp4'),bodyParser = require('body-解析器'),app = express(),ejs = require('ejs');
var plotly = require('plotly')(Patidar,ku0sisuxfm)


//解析应用程序/ x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:false}))
//解析应用程序/ json
app.use(bodyParser.json())
app.use(express.static ('上市'));

//读取输入页面的html文件
app.get('/',function(req,res){
var html = fs.readFileSync('index2 .html');
res.writeHead(200,{'Content-Type':'text / html'});
res.end(html);
});

//在html文件中读取输出页面
app.get('/ output',function(req,res){
var html = fs.readFileSync('index4 .html');
res.writeHead(200,{'Content-Type':'text / html'});
res.end(html);
});

//接收UDP消息

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

if(once ==Once){
//定义UDP
的主机和端口值var HOST = req.body.ip;
var PORT = req.body.port;
//读取用户命令,转换为十六进制
var message = new Buffer(req.body.number,'hex');

//发送数据包到TFTP

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

//接收消息并将其打印到网页
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(); //这里你指定了需要值的临时变量

var renderedHtml = ejs.render(content,{temp:temp, host:HOST,port:PORT}); //获取被重写的HTML代码
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);
}
//定义UDP的主机和端口值
var HOST = req.body.ip;
var PORT = req.body.port;
//读入用户的命令,转换为十六进制
var message = new Buffer(req.body.number,'hex');

//将数据包发送到TFTP

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

//接收消息返回并打印到网页

client.on('message',function(message){
fs.readFile('index3.html','utf-8',function(错误,内容){
if(err){
res.end('error occurred');
return;
}
var temp = message.toString( ); //在这里你指定一个带有所需值的临时变量

var renderedHtml = ejs.render(content,{temp:temp,host: HOST,port:PORT}); //获取被重写的HTML代码
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);
}
});



//设置监听服务器
app.listen(3000,192.168.0.136);
console.log('听取192.168.0.136:3000');

我有两个按钮,一个按钮发送一次UDP数据包,而一个连续按钮发送相同的UDP数据包每10秒钟一次。但是,当按下此按钮时,res.write将再次重复整个输出。看看附加的图片,看看输出[![enter image description here] [1]] [1]

解决方案

你的代码放到一个自动代码格式化器中以使其可读,我可以看到你正在这样做:

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

app.post()处理程序,这意味着每次调用您的后处理程序时,都会添加另一个 client.on('message',...) code>事件处理程序。所以,第二次调用之后,你有两个事件处理程序,第三次调用之后,你有三个事件处理程序,等等。



<因此,只要你有这些重复,每一个将被调用,你会得到重复的行动。



您的选择是:


  1. 对事件处理程序使用 .once(),以便在触发后自动删除它。

  2. 火灾发生后手动将其删除或者当你完成它的时候。

  3. 在你的 app.post()处理程序之外添加一次,所以你永远不会添加重复项。 / li>
  4. 重构代码的工作方式,使其不存在此类问题。例如,对于相同的传入消息,您有两个不同的处理程序。这是非常有状态的代码的一个标志,写得更加复杂。一种更好的设计不会以这种方式呈现状态会更简单。


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

解决方案

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.

这篇关于连续发送UDP数据包时,Res.write不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆