Question

I'm trying to write a basic chat application with Node.js (Express), and Socket.io. Everything 'seems' to be working, but my socket server seems to be only 'sending' the message back to the original sender. Here is my socket code:

var client = io.listen(app);

client.sockets.on('connection', function (socket) {
  socket.on('message', function (data) {
    console.log(data);
    socket.send(data);
  });
});

And here is my client side code:

$(document).ready(function() {
    var socket = new io.connect('http://localhost:3000');

    socket.on('connect', function() {
        socket.send('A client connected.');
    });

    socket.on('message', function(message) {
        $('#messages').html('<p>' + message + '</p>' +  $('#messages').html());
        console.log(socket);

    });

    $('input').keydown(function(event) {
        if(event.keyCode === 13) {   
            socket.send($('input').val());
            $('input').val('');
        }
    });
});

Help is appreciated.

Was it helpful?

Solution

Use client.sockets.emit instead of socket.emit. It will emit to every connected client (broadcast), using the socket object only sends to the specific client.

OTHER TIPS

Server side, I think you want:

socket.broadcast.emit(data);

instead of:

socket.send(data);

See "Broadcasting Messages" at the bottom of the "How to use" page. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top