owl
owl

Reputation: 4461

Send message to all users + yourself (Socket.io)

client-side javascript file:

socket.on('message', function(msg) {
    $(".chat-body").append(msg);
});

$("form").submit(function(e) {
    e.preventDefault();
    var msg = $("input[type=text]").val();
    socket.send(msg);
});

server-side app.js:

io.sockets.on('connection', function(socket) {
    socket.on('message', function(data) {
      socket.broadcast.send(data);
    });
    socket.on('disconnect', function() {
      // handle disconnect
    });
});

How to send message to yourself too without additional "append"?

Thanks in advance.

Upvotes: 1

Views: 5012

Answers (2)

CommonSenseCode
CommonSenseCode

Reputation: 25369

socketis the current socket that started event connection now you want to emit to all users + yourself use:

io.sockets.emit('message', msg);

If you want to send to all sockets except yourself use broadcast.emit("event", value):

socket.broadcast.emit('event', msg)

If you just want to answer yourself (socket that initiated event):

socket.emit('msg_socket', msg);

Upvotes: 5

sgress454
sgress454

Reputation: 24948

Well, according to the documentation, it's:

// sending to all clients, include sender
io.sockets.emit('message', data);

It may also be possible to do:

io.sockets.send(data);

but it would be doing the same thing, so I'd go with the documented way.

Upvotes: 2

Related Questions