Query socket io in nodejs

3

I try to send data from a client to an endpoint in nodejs and with socket io graph this in real time on a graph of temperatura vs tiempo .

Part of the client:

else{

  sensors=["Rimac","Cercado"];

  for (sensor in sensors){
  var date = new Date().toJSON();

  var datos={
    name:sensors[sensor],
    valor:Math.random()*20,
    fecha:date
  };

console.log(datos);
    var options = {
  uri: 'http://localhost:7777/api/sensor',
  method: 'POST',
   headers: {
        "content-type": "application/json",
        },
  json: datos
};

  request(options);
  sleep(1000);


};

The data is sent normally to the designated endpoint.

This is the part of the server where the endpoint is that receives the request

module.exports=function(app,Sensor,io){
var express=require("express");
var router=require("express").Router(); 

  router.route("/sensor").get(function (req, res){
  Sensor.find(
    function(err, Sensor) {
      if (err)
        res.send(err)
      else{
        console.log("Exito al retornar todo");
        res.json(Sensor);

      }
      // devuelve todas las Sensors en JSON
        }
      );
}).post(function(req,res){
  console.log("BODY=");
  console.log(req.body)
    Sensor.create(
    {
    name:req.body.name,
     valor:req.body.valor,
     fecha:req.body.fecha
   } ,
      function(err) {
        if (err){
          console.log(err);
          res.send(err);
        }
        else{
          io.sockets.on("connection",function(socket){

             var temp = parseFloat(req.body.valor);
        var date = new Date(req.body.fecha); 
        console.log(date);
        console.log(temp);
        //Se pasan los datos a el cliente web ahi se manejara para mostrar la grafica en tiempo real mediante higcharts
        socket.emit('post', date.getTime() - ( date.getTimezoneOffset() * 60000) , temp );    
          })
       console.log("Dato creado exitosamente");
}

});

});
  return router;
}

This is the part of the view that receives the data that comes by post (this should be but not shown, but I have to update for the changes to be effective).

  var socket = io.connect('http://localhost:7777/');

    var chart;

    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'chart', 
            defaultSeriesType: 'spline',
            events: {
                load: function() {
                    // Cada vez que reciba un valor desde el socket, lo meto en la gráfica
                    socket.on('post', function ( time, data ) {
                        console.log("LLEGO DATO O NO?");
                        console.log(data);
                        console.log("TIEMPO");
                        console.log(time);

                        var series = chart.series[0];
                        series.addPoint([time, data]);
                    });
                }
            }
        },
        rangeSelector : {
            selected : 100
        },
        title: {
            text: 'Datos del Sensor de temperatura'
        },
        xAxis: {
            type:'datetime',
            tickPixelInterval: 50,
            maxZoom: 20 * 1000
        },
        yAxis: {
            minPadding: 0.1,
            maxPadding: 0.1,
            title: {
                text: 'Valores',
                margin: 10
            }
        },
        series: [{
            name: 'Sensor Temperatura',
            data: []
        }]
    });

The question is in the part of the endpoint that receives the data, they arrive intact, but when I review I see that the socket is skipped and sends me defrente to the message console.log ("Data created successfully"); , and it does not show in real time the states in the chart in highcharts, so that the changes are effective I have to update the window, and just then the data appear in the console (which should appear before sending the data).

Edit:

Viewing the logs with morgan, when the data is sent the 2 take the same date / time, I guess this is because of the synchronicity issue that I have to put on date, and also the post request is not shown until it is closes the client, it's like keeping the connection alive.

    
asked by Kevin AB 06.07.2016 в 11:22
source

1 answer

1

Well since the solutions was just put io.sockets.emit in a line and delete the io.sockets.on("connection"... because I will not hear events just send them.

    
answered by 06.07.2016 / 14:25
source