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

后端 未结 6 1926
日久生厌
日久生厌 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: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);
    });
    

提交回复
热议问题