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

后端 未结 6 1927
日久生厌
日久生厌 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 04:48

    Simple and precise (Source: Socket.IO google group):

    socket.emit allows you to emit custom events on the server and client

    socket.send sends messages which are received with the 'message' event

    0 讨论(0)
  • 2020-12-02 04:51

    https://socket.io/docs/client-api/#socket-send-args-ack

    socket.send // Sends a message event

    socket.emit(eventName[, ...args][, ack]) // you can custom eventName

    0 讨论(0)
  • 2020-12-02 04:59

    With socket.emit you can register custom event like that:

    server:

    var io = require('socket.io').listen(80);
    
    io.sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });
    

    client:

    var socket = io.connect('http://localhost');
    socket.on('news', function (data) {
      console.log(data);
      socket.emit('my other event', { my: 'data' });
    });
    

    Socket.send does the same, but you don't register to 'news' but to message:

    server:

    var io = require('socket.io').listen(80);
    
    io.sockets.on('connection', function (socket) {
      socket.send('hi');
    });
    

    client:

    var socket = io.connect('http://localhost');
    socket.on('message', function (message) {
      console.log(message);
    });
    
    0 讨论(0)
  • 2020-12-02 05:00

    socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

    0 讨论(0)
  • 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
        }));
    }
    
    0 讨论(0)
  • 2020-12-02 05:05

    In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes

    0 讨论(0)
提交回复
热议问题