N
N
nurdus2017-09-21 01:51:07
Socket.io
nurdus, 2017-09-21 01:51:07

Why doesn't socket.emit work as expected?

Good day.
There is a test case:

// server.js
// ...
let io = require('socket.io');
io = io(expressServer);
io = io.listen(expressServer);
io.on('connection', function (socket) {
  socket.on('message', function (data) {
    //socket.broadcast.emit('message', data); // (1)
    socket.emit('message', data); // (2)
    console.log(data);
  });
});

// client.js
// ...
let chat = io.connect(config.wssHost);
chat.on('connect', function() {
  chat.on('message', function(message){
        console.log(message);
    });	            
});
// отправка происходит так (полный код не буду приводить): 
chat.emit('message', chatMessage);

(1) - works correctly, sending a response to everyone except the client that sent the 'message'.
(2) - does NOT work correctly, sending a response only to itself.
Question: why?!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Hellsite, 2017-09-21
@nurdus

const chat = io.connect(config.wssHost);

// Иначе при переподключении будут дублироваться
chat.on('connect', function() {
  console.log('Connected');
});


chat.on('message', function(message){
  console.log(message);
});

And secondly, on the server, you need to send not to the current socket, but to everyone.
io.on('connection', function (socket) {
  socket.on('message', function (data) {
    //socket.broadcast.emit('message', data); // (1)
    console.log(data);
    io.sockets.emit('message', data);
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question