Luiz Henrique Luiz Henrique - 1 year ago 79
HTML Question

Socket I.o doesn't automatically update

I am using the Socket ith and when I send a POST / EnviaTemperatura is not updating automatically on my site. what am I doing wrong?

Node.js'/EnviaTemperatura', function(req, res){
temperatura = req.body.temp;
res.send('Temperatura: ' + temperatura);

io.on("connection", function(socket) {
socket.emit('RecebTemp', temperatura);


<div class="col-xs-9 text-right">
<div class="huge"><span id="EnviaTemp">0</span> ÂșC</div>
<div>Temperatura no Interior da casa</div>

var socket = io();
socket.on('RecebTemp', function (temperatura) {
document.getElementById("EnviaTemp").innerHTML = temperatura;

In my case, it is only updating when I the one Refresh the page. But I did not want to refresh the entire page, only that DIV, as have other elements on the screen that take a while to load.

What could it be?

Answer Source

Try this:

'use strict';
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const temperatureSender = new MyEmitter();

and then inside the

temperatureSender.emit( 'sendTemp', temperature);

and inside the io.on('connection',..):

temperatureSender.on('sendTemp', function(temperature) {
    socket.emit('RecebTemp', temperature);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download