我如何处理 Socket.io 中的关闭事件? [英] How can i handle Close event in Socket.io?

查看:182
本文介绍了我如何处理 Socket.io 中的关闭事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作基于 Web 的简单在线游戏.游戏使用 Socket.io 互相联网.但我遇到了问题.

I'm making simple online game which based on Web. the game uses Socket.io for netwoking each other. but I encountered the problem.

考虑以下情况.我运行了 Socket.io 服务器.一名玩家制作房间,另一名玩家加入房间.他们玩了一段时间游戏..但是一位玩家非常生气并关闭了游戏标签.

think about following situation . I ran Socket.io server. one player making the room , and other player join the room. they played game some time .. but one player so angry and close the game tab.

在这种情况下,如何在服务器端获取一个客户端关闭浏览器的事件?

in this situation , how can I get the event which one client have been closed the browser in server-side ?

根据谷歌搜索,人们这样说:使用浏览器关闭事件,如 onBeforeUnload"

according to googling , peoples say like this : "use browser-close event like onBeforeUnload"

但我知道所有浏览器都不支持 onBeforeUnload 事件.所以我想要解决方案在 SERVER SIDE 检查客户端断开连接事件.

but I know that All browser don't support onBeforeUnload event. so i want solution about checking the client disconnection event in SERVER SIDE.

在 Socket.io ( nodeJS ) 服务器端控制台,当客户端的连接关闭时,控制台显示如下:

in Socket.io ( nodeJS ) server-side console , when client's connection closed , the console say like following :

调试 - 丢弃传输

我的 nodeJS 版本是 0.4.10,Socket.io 版本是 0.8.7.并且两者都在 Linux 上运行.

My nodeJS version is 0.4.10 and Socket.io version is 0.8.7. and both are running on Linux.

有人可以帮忙吗?

短代码在这里:

var io = require ( "socket.io" ).listen ( 3335 );
io.sockets.on ( "connection" , function ( socket )
{
  socket.on ( "req_create_room" , function ( roomId ) 
  {
    var socketInstance = io
    .of ( "/" + roomId )
    .on ( "connection" , function ( sock )
    {
       sock.on ( "disconnect" , function () 
       {
          // i want this socket data always displayed...
          // but first-connected-client doesn't fire this event ..
          console.log ( sock );
       }
    });
  });
});

推荐答案

更新: 我创建了 一篇博文 用于此解决方案.欢迎任何反馈!

Update: I created a blog post for this solution. Any feedback is welcome!

我建议对 Socket IO 使用卸载时同步断开连接"选项.我遇到了类似的问题,这真的帮了我.

I recommend using the 'sync disconnect on unload' option for Socket IO. I was having similar problems, and this really helped me out.

在客户端:

var socket = io.connect(<your_url>, {
'sync disconnect on unload': true });

无需连接任何unloadbeforeunload 事件.在多个浏览器中尝试了这一点,到目前为止效果很好.

No need to wire in any unload or beforeunload events. Tried this out in several browsers, and its worked perfectly so far.

这篇关于我如何处理 Socket.io 中的关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆