简体   繁体   中英

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

I made a simple app that uses socket.io for sending messages.

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

Have any ideas? If you think that I wrote something wrong, feel free to say it (for example x++ instead x += 1) .

socket.in or socket.to not working in client and you should use it in server side.

Socket.io Documentation

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');
Refer: socket-io docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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