本文介绍了Socket.io如何判断某人何时离开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用socket.io创建一个实时游戏.目前,当有人离开时,什么也没有发生.我想以某种方式通知服务器说谁离开了.有没有一种方法可以在用户离开时发出正确的消息?我能否让服务器每隔1000毫秒对每个人执行一次ping操作,或告诉别人仍在连接状态?

I am creating a real-time game with socket.io. Currently, when somebody leaves, nothing happens. I would like to somehow notify the server to say who left. Is there a way to emit something right as a user leaves? Can I have the server ping everybody every 1000ms or something to tell who's still connected?

推荐答案

在关闭窗口/页面之前,发出一个包含用户详细信息的事件,然后添加一个事件侦听器以监听该频道.事件侦听器可以从收到的消息中获取用户详细信息.显示它.

Before closing the window/page emit an event containing user detail, on add a event listener to listen to that channel. The event listener could get user detail from message received & show it.

草稿:

// server code
socket.on('user_left', function(user){
   // broadcast user to channel 'user_left_group'
});

// browser - for other users
socket.on('user_left_group', function(user){
     // code to show user left
}

// browser - to say I am leaving
socket.emit('user_left', myname);

这篇关于Socket.io如何判断某人何时离开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 21:12