I started a simple express+socket.io project. On the server I registered to socket's 'connection' event and upon that I send a message to the client. This works well.
When I receive the message on client side from the server, in this event handler i do socket.emit('message', 'some text');
This message doens't arrive to server. I know it should be very simple and thus I think i missing something stupid. Any help appreciated.
server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
console.log('a user connected');
io.emit('server-message', 'hello socket.io server');
});
io.on('message', function(message) {
console.log(message);
});
client code:
window.socket = io.connect('http://localhost:3000');
socket.on('server-message', function (message) {
console.log(message);
socket.emit('message', 'hello socket.io from browser');
});
Looks like io.emit('server-message', 'hello socket.io server');
should be changed to socket.emit('server-message', 'hello socket.io server');
You would then need to move the following into the connection
event listener:
io.on('message', function(message) {
console.log(message);
});
and change it to
socket.on('message', function(message) {
console.log(message);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With