【问题标题】:Socket.io - TypeError: socket.in is not a functionSocket.io - TypeError:socket.in 不是函数
【发布时间】:2018-08-03 11:41:11
【问题描述】:

我制作了一个使用 socket.io 发送消息的简单应用。

这里是服务器代码片段:

var io = require('socket.io')(http);

io.on('connection', function(socket) {
  console.log('a user connected');

  socket.on('disconnect', function() {
    console.log('user disconnected');
  });

  socket.on('connect to room', function(rooms) {
    for (var i = 0; i < rooms.length; i++) {
      socket.join(i);
      console.log('joined to room number ' + i);
    }
  });

  socket.on('chat message', function(id, msg) {
    console.log('message!');
    io.broadcast.to(id).emit('chat message', msg);
  });
});

这是客户端代码:

var socket = io('http://localhost:8080');

socket.on('connect', function(socket) {
  console.log('you have been connected!');
});

socket.on('chat message', function(msg) {
  console.log('message!');
  $('#messages').append(msg);
});

socket.emit('connect to room', [{
  {
    user.rooms
  }
}]);

if (e.which == 13 && target.is('#message')) {
  var message_text = $('#message').val();
  socket.in(room.id).emit(message_text);
  $(#messages).append(message_text);
}

(房间对象是当前打开的房间) 运行后出现错误:

未捕获的类型错误:socket.in 不是函数

有什么想法吗?如果您认为我写错了,请随时说(for example x++ instead x += 1)

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    socket.insocket.to 在客户端不工作,你应该在服务器端使用它。

    Socket.io Documentation

    例如:

    io.on('connection', (socket) => {
    
      // to one room
      socket.to('others').emit('an event', { some: 'data' });
    
      // to multiple rooms
      socket.to('room1').to('room2').emit('hello');
    
      // a private message to another socket
      socket.to(/* another socket id */).emit('hey');
    
      // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
      // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
    });
    

    【讨论】:

      【解决方案2】:

      它将是socket.to('some room').emit('some event');
      参考:socket-io docs

      【讨论】:

        猜你喜欢
        • 2018-03-03
        • 2012-01-26
        • 2015-09-22
        • 2021-05-12
        • 1970-01-01
        • 2018-08-03
        • 2016-01-14
        • 2018-08-27
        • 1970-01-01
        相关资源
        最近更新 更多