socket.emit() vs. socket.send()

后端 未结 6 1929
日久生厌
日久生厌 2020-12-02 04:04

What\'s the difference between these two?

I noticed that if I changed from socket.emit to socket.send in a working program, the server fail

6条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:03

    TL;DR:

    socket.send(data, callback) is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)

    Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?

    So yeah basically emit allows you to send objects, which is very handy.

    Take this example with socket.emit:

    sendMessage: function(type, message) {
        socket.emit('message', {
            type: type,
            message: message
        });
    }
    

    and for those keeping score at home, here is what it looks like using socket.send:

    sendMessage: function(type, message) {
        socket.send(JSON.stringify({
            type: type,
            message: message
        }));
    }
    

提交回复
热议问题