socket.io 判断用户是在线还是离线 [英] socket.io determine if a user is online or offline
本文介绍了socket.io 判断用户是在线还是离线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以通过这个代码追踪连接是建立还是断开
We can trace if a connection is established or disconnected by this code
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
嗯,没问题.但是我们如何确定哪些用户已连接或脱机.我的客户端是用 PHP/HTML
编写的,所以他们有一个用户 ID.
Well, its fine. But how can we determine what user connected or gone offline. My client is written in PHP/HTML
so they have a user ID.
推荐答案
如果您的客户端有特定的用户 ID,他们需要将它们发送到 socket.io 服务器.例如.在客户端你可以做
If your clients have specific user IDs they need to send them to socket.io server. E.g. on client side you can do
<script>
const socket = io();
socket.emit('login',{userId:'YourUserID'});
</script>
在服务器上你会放一些类似的东西
And on server you will put something like
const users = {};
io.on('connection', function(socket){
console.log('a user connected');
socket.on('login', function(data){
console.log('a user ' + data.userId + ' connected');
// saving userId to object with socket ID
users[socket.id] = data.userId;
});
socket.on('disconnect', function(){
console.log('user ' + users[socket.id] + ' disconnected');
// remove saved socket from users object
delete users[socket.id];
});
});
现在您可以将套接字 ID 与您的用户 ID 配对并使用它.
Now you can pair socket ID to your user ID and work with it.
这篇关于socket.io 判断用户是在线还是离线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文