Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server not receiving client's socket.io message

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');
         });
like image 596
Gal Ziv Avatar asked Jul 13 '16 17:07

Gal Ziv


1 Answers

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);
});
like image 143
Evan Lucas Avatar answered Oct 21 '22 00:10

Evan Lucas