gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:43:20 26 4
gpt4 key购买 nike

我制作了一个使用 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);
}

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

Uncaught TypeError: socket.in is not a function

有什么想法吗?如果您认为我写错了什么,请随时指出来 (例如 x++ 而不是 x += 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.
});

关于javascript - Socket.io - TypeError : socket. in is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com