【发布时间】:2016-04-26 20:19:15
【问题描述】:
我正在尝试通过构建一组动态创建的聊天室来学习 Socket.io,这些聊天室会在用户进入和离开时发出“连接”和“断开”消息。在查看couple of questions 之后,我整理了一些功能性的东西,但大多数相关的响应来自承认他们已经将答案拼凑在一起的人,我注意到有一个更普遍的 - 也是最近的 -在 Socket.io 存储库上讨论正确的方法(特别是 here 和 here)
由于我是一个新手,我不知道下面的工作是否是一种可接受的做事方式,或者它只是偶然发挥作用,但会导致性能问题或导致过多的听众。如果有一种理想且正式的方式来加入和离开感觉不那么笨重的房间,我很乐意了解它。
客户
var roomId = ChatRoomData._id // comes from a factory
function init() {
// Make sure the Socket is connected
if (!Socket.socket) {
Socket.connect();
}
// Sends roomId to server
Socket.on('connect', function() {
Socket.emit('room', roomId);
});
// Remove the event listener when the controller instance is destroyed
$scope.$on('$destroy', function () {
Socket.removeListener('connect');
});
}
init();
服务器
io.sockets.once('connection', function(socket){
socket.on('room', function(room){ // take room variable from client side
socket.join(room) // and join it
io.sockets.in(room).emit('message', { // Emits a status message to the connect room when a socket client is connected
type: 'status',
text: 'Is now connected',
created: Date.now(),
username: socket.request.user.username
});
socket.on('disconnect', function () { // Emits a status message to the connected room when a socket client is disconnected
io.sockets.in(room).emit({
type: 'status',
text: 'disconnected',
created: Date.now(),
username: socket.request.user.username
});
})
});
【问题讨论】:
-
我的回答有用吗?
-
第一次看到它现在和很久以前一起破解了一些东西,但这似乎是我想要的:)