2016-06-24 2 views
0
//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')("Patidar2", "9z2dlsvsqn") 


// 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); 
     }); */ 
    }); 
    }); 
} 

//Send UDP packet continuously every ten seconds 
    if (once == "continuous") { 
    var timesRun = 0; 
    var requestLoop = setInterval(function(){ 
    timesRun += 1; 
     if(timesRun === 2){ 
     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; 
     }); 
}, 10000); 
//Recieving message back and printing it out to webpage 


    client.on('message', function (message) { 
     var HOST= req.body.ip; 
     var PORT= req.body.port; 
     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); 
     //}); 
    }); 
    }); 
} 
}); 



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

setInterval을 사용하여 10 초마다 동일한 UDP 패킷을 보내는 연속 단추를 만들었지 만, 나는 index3.html에서 읽었습니다. 그 html 파일은 메시지가 수신 될 때마다 복제됩니다. 사진이 그걸 보여줍니다. 각 패킷 이후에 출력을 업데이트 할 수 있기를 원합니다.파일을 노드 js에 한 번 작성한 후 res.write를 지우시겠습니까?

답변

0

서버가 향후 업데이트를 페이지에 보낼 수있게하려면 (여기에서 해결하려는 실제 문제가 무엇인지 추측합니다) http 요청/응답이 올바른 아키텍처가 아닙니다. 모든.

대신 서버에서 해당 데이터를 수신하고 원하는 방식으로 페이지에 삽입 할 수있게하려는 경우 서버가 페이지에 데이터를 보낼 수있는 서버 푸시 양식이 필요합니다.

요즘의 일반적인 메커니즘은 webSocket 또는 그 상위 버전 인 socket.io입니다.

socket.io 스키마에서 서버는 들어오는 socket.io 연결에 대한 수신기를 설정합니다. 그런 다음 업데이트를받을 수있는 모든 페이지에서 서버에 대한 socket.io 연결을 만들고 특정 메시지에 대한 리스너를 등록합니다. 그런 다음 서버에 관심이 생기고 하나 이상의 연결된 웹 페이지에 알리려고하면 서버는 socket.io 메시지를 해당 웹 페이지로 보낼 수 있습니다. 웹 페이지는 그 메시지를 수신하고 원하는대로 처리 할 수 ​​있습니다 (예 : 현재 표시된 웹 페이지를 새 데이터로 업데이트).

socket.io에 대한 자세한 내용은 http://socket.io/을 참조하십시오.


웹 소켓 외에 다른 옵션은 정기적으로 서버에 아약스 호출을 보낼 수있는 웹 페이지에 대하고는이 것을 서버가 새로운 데이터를 반환 할 수있는 클라이언트 수있는 다음과 유사한 데이터 처리 (webSocket이 전송 된 데이터를 처리하는 방법). 이를 클라이언트 폴링이라고합니다. 구현이 약간 더 간단 할 수도 있지만, 확장 성이 떨어지며 응답 성이 떨어지는 경우가 많습니다. 클라이언트가 새롭고 대부분의 경우 서버가 "새로운 것은 없습니다"라는 응답이있을 때마다 정기적으로 서버에 요청해야하기 때문입니다. 향후


, 난 당신이 같은 일 here, herehere 매우 가까운 세 가지 질문을 게시하지 않도록 건의 할 것입니다. 질문을 다시 게시하기보다는 명확하게 편집해야합니다. 그리고 새로운 질문은 이전 질문과 크게 달라야합니다. 질문에 대한 답변을 얻지 못하면 요청한 내용이 명확하지 않기 때문일 수 있습니다.

+0

소켓을 사용하는 것이 가장 좋은 방법이라는 것을 알고 있지만, 소켓을 사용하여 같은 디자인을 구현하는 방법에 대해서는 너무 분실했습니다. 소켓과 함께 app.post와 같은 것을 구현할 수 있습니까? – lord

+0

@patidar - 앞서 설명한 것처럼 동일한 것을 구현하지 않습니다. 서버 쪽 알림을 얻으려면 새로운 아키텍처가 필요합니다. 'app.post()'에서 알림을 보내려고하면 잘못된 디자인 일 뿐이므로 작동하지 않습니다. – jfriend00

관련 문제