简体   繁体   English

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

[英]Socket.io - TypeError: socket.in is not a function

I made a simple app that uses socket.io for sending messages. 我创建了一个使用socket.io发送消息的简单应用程序。

Here the server code piece: 这里的服务器代码片段:

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

And here is the client code: 这是客户端代码:

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

(The room object is the current opened room) After I ran it I got an error: (房间对象是当前打开的房间)我运行它之后出现错误:

Uncaught TypeError: socket.in is not a function 未捕获的TypeError:socket.in不是函数

Have any ideas? 有什么想法吗? If you think that I wrote something wrong, feel free to say it (for example x++ instead x += 1) . 如果您认为我写错了,请随意说出来(for example x++ instead x += 1)

socket.in or socket.to not working in client and you should use it in server side. socket.insocket.to无法在客户端工作,你应该在服务器端使用它。

Socket.io Documentation Socket.io文档

for example : 例如 :

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM