Search code examples
jquerynode.jssocket.iomultiplayer

socket.on() and socket.emit() failure


I'm trying to make it so when a user presses a button, the background of a div will change color for all of the users. But that's not happening. It is a problem with my socket.on and socket.emit. Here is my code.

Server-Side

var express = require('express');
var routes = require('./routes');
var io = require('socket.io');

var app = express();
var server = require('http').createServer(app);

app.configure(...);

app.get('/', routes.index);

server.listen(3000, function(){
    console.log('Listening on port 3000');
});

//Attach socket.io
var io = io.listen(server);

io.sockets.on('connection', function (socket) {
    console.log('connection established');
    socket.on('background change event', function(button){
        console.log(button);
        if(button == 'button_1')
            socket.emit('background change', 'red');
        else if(button == 'button_2')
            socket.emit('background change', 'green');
        else if(button == 'button_3')
            socket.emit('background change', 'blue');
    });
});

Client-Side

var socket = io.connect();

$(document).ready(){
    var buttons = [$('#button_1'), $('#button_2'), $('#button_3')];
    $.each(buttons, function(i, val){
        val.click(function(){
            console.log('clicked ' + val.attr('id'));
            socket.emit('change background event', val.attr('id'));
        });
    });

    socket.on('change background', function(color){
        console.log(color);
        $('#change_my_background').css('background-color',color);
    });
});

When I connect to the page, the server logs connection established so we at least made it to that point. Then I click a button, and the client logs clicked button_1 and that's the last of the logging. So it seems that the problem lies with either socket.emit('change background event', val.attr('id')) or socket.on('background change event', function(button){...}).

I have tried changing my socket.emit statement to send the id in an object like on some of the socket.io examples, but that didn't work either. So what do I need to change to make this work?

P.S. Here is my version information:

node.js    0.8.11
express    3.0.0rc4
socket.io  0.9.10

Solution

  • On client you have socket.on("change background", function...) instead of background change, which is the emit you're doing on the server.