Robert Robert - 4 months ago 25
Javascript Question

Socket io only emits data upon page reload

Within an express.js project I am attempting to emit data from the nodeJS server to the client.

Upon reaching the page the terminal (from which I initiated the server) states a user has connected via socket. However upon running the function that contains the socket emit function, nothing occurs.

Only upon reloading the webpage does the emitted data appear in the html and terminal console logs.

Below is the code triggering the socket from within a Callback function, in app.js

foo(function(fooCallback) {
console.log('Callback triggered');

io.on('connection', function(socket) {
console.log('about to send data via socket');
io.sockets.emit('person', { 'name': 'Jack Smith' });

});
});


global.js - (client side js loaded after jquery and socket scripts)

var socket = io.connect();
socket.on('person', function(socket){
console.log('client recieved something from socket');
var personName = socket.name;
$('#person').html(personName);
});


Why is data only being emitted when the webpage is reloaded, rather than automatically?

Answer

In this section of code:

io.on('connection', function(socket) {
    console.log('about to send data via socket');
    io.sockets.emit('person', { 'name': 'Jack Smith' });
});

You say that you only want to run io.sockets.emit('person', { 'name': 'Jack Smith' }); when the io variable first connects. Try changing this to:

io.on('connection', function(socket) {
    console.log('about to send data via socket');
});

io.sockets.emit('person', { 'name': 'Jack Smith' });