Reputation: 151
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:
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:
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:
├── [email protected]
└─┬ [email protected]
├── [email protected]
├── [email protected]
└─┬ [email protected]
├─┬ [email protected]
│ └── [email protected]
├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ └── [email protected]
└── [email protected]
Thanks for any assistance.
Upvotes: 0
Views: 3651
Reputation: 5292
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.
Upvotes: 3