[英]Socket.io - TypeError: socket.in is not a function
我創建了一個使用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)
。
socket.in
或socket.to
無法在客戶端工作,你應該在服務器端使用它。
例如 :
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.
});
它將是socket.to('some room').emit('some event');
請參閱: socket-io docs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.