Why socket.io on server not running continuously?

I've a node api(POST)in which the sensor keep on pushing the data to the MongoDB. Now before inserting the data into the DB, I need to pass that to the HTML page. To get the continuous stream of data, I've used SOCKET.IO module. The data should be displayed on html page using SOCKET.IO-CLIENT. But the problem I'm getting here is, for the initial execution of API route, it's getting the data and displayed on page. But for the 2nd time of api execution, the data is saving in to the db but not displaying on the html page. Please have a look at my code.

POST API

AddDeviceLogs:async function(templateId, payload){
    let err, deviceData;
    payload.template=templateId;
    const myCollection=templateId;
    var io = require('socket.io')(server);
    io.on('connection',function(socket){
        socket.emit('data', payload); 
    });

    app.get('/',function(req,res) {
        res.sendFile('C:/Users/user/Desktop/data.html');
    });

    [err, deviceData]=await to(mongoose.connection.db.collection(myCollection).insert(payload));
    if(err) TE(err.message, true);
    return (deviceData)? deviceData.result:false;
},

HTML

<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
        <!--<script src='https://cdn.socket.io/socket.io-1.2.0.js'></script>-->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
    </head>
    <body>
        <script>
            var socket = io.connect("http://localhost:3000/",{"forceNew": true});
            socket.on('data', function(data){
                $('#deviceid').text(data.deviceId);
            });
            socket.on('data', function(data){
                $('#heat').text(data.heat);
            });
            socket.on('data', function(data){
                $('#humidity').text(data.humidity);
            });
        </script>
        <h4>Welcome to socket.io testing program!</h4>
        <div id="deviceid"></div>
        <div id="heat"></div>
        <div id="humidity"></div>
    </body>
</html>

sample output of html page. The details are need to changed frequently. But I couldn't able to solve the issue here.

1 answer

  • answered 2019-11-09 13:02 lamtacvu

    Assume your AddDeviceLogs is called by your sensor.

    var io = require('socket.io')(server);
    var datas;
    io.on('connection',function(socket){
        if (datas)
            socket.emit('data', payload); 
    });
    
    async function AddDeviceLogs(templateId, payload){
        let err, deviceData;
        payload.template=templateId;
        const myCollection=templateId;
    
        io.emit('data', payload);         
    
        [err, deviceData]=await to(mongoose.connection.db.collection(myCollection).insert(payload));
        if(err) TE(err.message, true);
        return (deviceData)? deviceData.result:false;
    }
    app.get('/',function(req,res) {
        res.sendFile('C:/Users/user/Desktop/data.html');
    });