Can't send/emit from client to NodeJS server using sockets.io

I'm at my wits' end here so any help would be very much appreciated.

I'm trying to send or emit a message from my client (web page) to my Node.JS server via socket.io. This is on Windows 7 running as localhost.

The exact problem is:

  • I can send messages from the server to the client just fine.
  • Sending a message from the client to the server doesn't work :(

Server code:

// create http server
var app = require('http').createServer(httpHandler);
// socket.io
var io = require('socket.io').listen(app);

var port = 8080;

app.listen(port);
console.log('Server running at http://127.0.0.1:' + port);

// socket connection handler
io.sockets.on('connection', function (client) {
    // this works great:    
    client.emit('text_msg', {msg: 'Welcome you are now connected.'});

    // plain message - this never works :(
    io.sockets.on('message', function(data){
        console.log("*************************** message : " + data.txt);
    });
});

Here's is some of the client code:

<script src="/socket.io/socket.io.js"></script>

...snip...

var socket = io.connect( 'http://localhost' );
socket.emit('message', {txt:"test"});

socket.on('text_msg', function (data) {
    alert( data.msg );
});

I've tried the following browsers:

  • Chrome 18 (Windows 7)
  • Firefox 11 (Windows 7)
  • Internet Explorer 9 (Windows 7)

From NodeJS output, I can see both Chrome and Firefox use Websockets, and IE9 uses "htmlfile".

NodeJS is version 0.6.15

npm list looks like:

├── node-static@0.5.9
└─┬ socket.io@0.9.6
  ├── policyfile@0.0.4
  ├── redis@0.6.7
  └─┬ socket.io-client@0.9.6
    ├─┬ active-x-obfuscator@0.0.1
    │ └── zeparser@0.0.5
    ├── uglify-js@1.2.5
    ├─┬ ws@0.4.13
    │ ├── commander@0.5.2
    │ └── options@0.0.3
    └── xmlhttprequest@1.2.2

Thanks for any assistance.

Change:

io.sockets.on('message', function(data){
console.log("*************************** message : " + data.txt);
});

To:

client.on('message', function(data){
console.log("*************************** message : " + data.txt);
});

When you call

io.sockets.on('connection', function (client)

you are defining "client" which is the current namespace for the socket that the client side is emitting from.