如何在页面更改时断开socket.io

时间:2017-11-28 15:41:25

标签: javascript socket.io

我想在我的网站上更改页面时断开套接字,只读取我所针对的特定传感器的读数,所有套接字的代码看起来大致相同,这里是温度传感器的代码(ds18b20)。

例如: 当我从温度页面更改为湿度页面时,我希望tempsocket关闭/断开,湿度插座打开,反之亦然。(每个传感器都有自己的javascript)

var value;  //Temperature sensor 1 values
var value2; //Temperature sensor 2 values

createGraph(); //Call the functions for it to make a clean graph at the start.

var values = []; //create an Array of values from Temperature sensor 1
var values2 = []; //create an Array of values from Temperature sensor 2

var times = []; //create an Array of times

var text = 'txtArea'; //enter the name of the text field

var chartColors = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(75, 192, 192)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(231,233,237)'
};
//---------------------Temperature1 + 2 ----------------------------------------
var tempsocket = io.connect('http://localhost:5000');

tempsocket.on('connect', function (){
    tempsocket.on('mqtt', function (msg){

  var elmarr=msg.topic.split("/");
  var elm=elmarr[3];

  if( elmarr.indexOf('Temp1') >= 0){//Temperature1 queue
    var sendData = "Internal: " + msg.payload;
    printText(text,elm,sendData); //Publish data to the textArea
    var value = (parseFloat(msg.payload)); //convert the string to float
    values.push(value); //Pass the temperature reading into the array
  };

  if( elmarr.indexOf('Temp2') >= 0){//Temperature2 queue
    var sendData2 = "External: " + msg.payload;
    printText(text,elm,sendData2); //Publish data to the textArea
    var value2 = (parseFloat(msg.payload)); //convert the string to float
    values2.push(value2); //Pass the temperature reading into the array
  };

  var d = new Date();//Get Date/Time for the times array
  var n = d.getHours()+ ":" + d.getMinutes()+ ":" + d.getSeconds();
  times.push(n);

    if(values.length > 6)//Delete the first value in the Temperature Array
    {
      values.splice(0, 1);
    }

    if(values2.length > 6)//Delete the first value in the Temperature Array
    {
      values2.splice(0, 1);
    }

    if(times.length > 6)//Delete the first value in the Time Array
    {
      times.splice(0, 1);
    }

  createGraph(values, values2, times);

});//Subscribe to the queue
     tempsocket.emit('subscribe',{topic:'SmartHive/Temperature/#'});
});
//-----------------------Print to Text Area-------------------------------------
function printText(chatID,ValueElm,PayloadValue){
  $('#'+chatID).append("\n" + PayloadValue);
  $('#'+chatID).scrollTop($('#'+chatID)[0].scrollHeight);
  $('#'.concat(ValueElm)).html(PayloadValue);
};
 //-----------------------Line Graph---------------------------------------------
//Function to create the line graph
function createGraph(dataValues, dataValues2, dataTimes){
  var options = {
  type: 'line',
  data: {
  labels: dataTimes,//Passing the array to be the labels
  datasets: [{
      label: 'Internal Temperature',
      data: dataValues,//Passing the array to be the data set
    borderColor: "#3e95cd",
    backgroundColor: "rgba(62, 149, 205, 0.4)",
    // backgroundColor: chartColors.red,
    // borderColor: chartColors.red,
    fill: true
    },
  {
      label: 'External Temperature',
      data: dataValues2,//Passing the array to be the data set
    borderColor: "#ff00e5",
    backgroundColor: "rgba(255, 0, 229, 0.4)",
    // backgroundColor: chartColors.blue,
    // borderColor: chartColors.blue,
    fill: true
    }
    ]
  },
  options: {
  responsive: true,
  // title: {
  //   display: true,
  //   text: 'Chart.js Line Chart'
  // },
  tooltips: {
    mode: 'label',
  },
  hover: {
    mode: 'nearest',
    intersect: true
  },
  scales: {
    xAxes: [{
      display: true,
      scaleLabel: {
        display: true,
        labelString: 'Time'
      }
    }],
    yAxes: [{
      display: true,
      scaleLabel: {
        display: true,
        labelString: 'Temperature'
      }
  }]
    }
  }
}
  var ctx = document.getElementById("myChart").getContext('2d');
  new Chart(ctx, options);
};

编辑:解决方案,我没有关闭给我提出问题的套接字,而是开始调用if语句中的所有内容,现在Chart工作得更好,我也没有做任何奇怪的事情。

if(elmarr.indexOf('Temperature') >= 0){

  if( elmarr.indexOf('Temp1') >= 0){//Temperature1 queue
    var value = (parseFloat(msg.payload)); //convert the string to float
    values.push(value); //Pass the temperature reading into the array
  };

  if( elmarr.indexOf('Temp2') >= 0){//Temperature2 queue
    var value2 = (parseFloat(msg.payload)); //convert the string to float
    values2.push(value2); //Pass the temperature reading into the array
    var d = new Date();//Get Date/Time for the times array
    var n = d.getHours()+ ":" + d.getMinutes()+ ":" + d.getSeconds();
    times.push(n);
    if(times.length > values.length || times.length > values2.length){
        EmptyArrays(values, values2, times);
    }else{
        createGraph(values, values2, times);
    };
  };

  if(values.length > 6)//Delete the first value in the Temperature Array
  {
    values.splice(0, 1);
  }

  if(values2.length > 6)//Delete the first value in the Temperature Array
  {
    values2.splice(0, 1);
  }

  if(times.length > 6)//Delete the first value in the Time Array
  {
    times.splice(0, 1);
  }
};

1 个答案:

答案 0 :(得分:2)

每当浏览器中的页面发生变化时,浏览器会自动关闭该页面中的任何webSockets或socket.io连接。事实上,你甚至无法阻止它们关闭。

因此,您所要做的就是确保 next 网页为下一页打开正确的套接字。前一个已经关闭。您的代码根本不清楚“打开湿度插座”的含义。

有许多方法可以打开套接字并向服务器指示您希望它发送哪种类型的数据。您可以向其发送一条消息,指出您希望它向您发送的数据类型。您可以请求连接到服务器将了解的特定命名空间(在socket.io中)。您可以要求加入将接收某些类型广播的特定房间。这完全取决于您希望如何配置和设计客户端和服务器。没有预设的方法。