문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top