phouse512
phouse512

Reputation: 680

Socket.io Client-Side socket not emitting

So I'm running a simple back-end node app with socket.io communicating with client side javascript running socket.io.

I can receive messages just fine on the client (I console log them), but the callback function where I emit an event back to the server is not being received. I think from what I've researched, there just might be some silently failing thing that I cannot see.

Client side code:

socket.on('connection', function(socket) {
    socket.on('welcome', function(data) {
        socket.emit('new_state', { data: '1' });
        console.log(data);
    });

    socket.emit('new_state', {data: '1'});

    socket.on('time', function(data) {
        console.log(data);
        socket.emit('new_state', {});
    });

    socket.on('updated_state', function(data) {
        console.log(data);
    });
});

Server Side:

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.sockets.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 3000);

// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
    socket.emit('welcome', { message: 'Welcome!' });
    console.log('connection received');

    io.sockets.on('i am client', function(data) {
        console.log(data);
    });

    io.sockets.on('new_state', function(data) {
        console.log('client->server emits');
        io.sockets.emit('updated_state', { state: [1,2,3,4] });
    });

});



app.listen(3000);

What's working right now is that the app.js logs the connection is received, but it never logs or recognizes any event received from the client. Any thoughts? I really think there's some silent error I am not getting.

Upvotes: 1

Views: 3063

Answers (1)

Cory Z A
Cory Z A

Reputation: 74

Use your callback socket inside of the connection. The namespace 'i am client' is never emitted from the front-end client, so it does nothing. On 'new-state' the server should be.

socket.on('new_state', function(data) {
    console.log('From Client ' + data);
    socket.emit('updated_state', { state: [1,2,3,4] });
});

Upvotes: 1

Related Questions