Socket.io-TypeError:socket.in不是函数

时间:2018-08-03 11:41:11

标签: javascript node.js socket.io

我制作了一个简单的应用,该应用使用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);
}

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

  

未捕获的TypeError:socket.in不是函数

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

2 个答案:

答案 0 :(得分:3)

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.
});

答案 1 :(得分:0)

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