注册用户离开PHP/JQuery Comet会话
我正在使用comet框架和以下代码在Codeigniter和JQuery中编写一个聊天客户端,其中doc_id是更新哪个聊天的标识 Javascript:注册用户离开PHP/JQuery Comet会话,php,javascript,jquery,ajax,comet,Php,Javascript,Jquery,Ajax,Comet,我正在使用comet框架和以下代码在Codeigniter和JQuery中编写一个聊天客户端,其中doc_id是更新哪个聊天的标识 Javascript: $(document).ready(function() { var timestamp = null; var doc_id = ($('#doc_id').length !== 0) ? $('#doc_id').val() : 'lobby'; //adapted from Comet tutorial at http://www.
$(document).ready(function() {
var timestamp = null;
var doc_id = ($('#doc_id').length !== 0) ? $('#doc_id').val() : 'lobby';
//adapted from Comet tutorial at http://www.screenr.com/SNH
function waitForMsg() {
//ping server and wait for response
$.ajax({
type: "GET",
url: "/index.php/documents/chat_call/" + timestamp + '/' + doc_id ,
async: true,
cache: false,
//when data comes back, parse, and then ping again
success: function(data) {
var json = $.parseJSON(data);
//code to update chat with JSON data
timestamp = json['timestamp'];
setTimeout(waitForMsg, 1000);
}
});
}
//immediately upon arrival, begin waiting for changes to chat
waitForMsg();
});
和PHP:
//adapted from Comet tutorial at http://www.screenr.com/SNH
function chat_call($browser_timestamp, $doc_id) {
//get name of flat file for chat
$filename = $_SERVER['DOCUMENT_ROOT'] . '/docs/log' . $doc_id . '.html';
//create file if it's not there
if (!file_exists($filename)) {
$handle = fopen($filename, 'w');
fclose($handle);
}
//time submitted by the browser
$lastmodif = isset($browser_timestamp) ? $browser_timestamp : 0;
//time of last change to file
$currentmodif = filemtime($filename);
//wait until file has been changed more recently than browser call
while ($currentmodif <= $lastmodif) {
usleep(1000);
clearstatcache();
$currentmodif = filemtime($filename);
}
//get contents of file and return as JSON
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
}
就目前而言,所有这些都运行得很好,我还有另一个功能,它可以在用户到达时通知用户,并向平面文件添加适用的通知。我遇到的麻烦是注册用户的离开。似乎当while循环中断时,我应该能够处理一些事情,但我不知道具体如何处理
我一直在研究诸如register\u shutdown\u函数和connection\u aborted之类的函数,但我不确定它们应该放在PHP函数中的什么位置。谁能告诉我这里最好的方法是什么
顺便说一句,我在SO上做了一些搜索,我知道这里很多人都建议使用node.js。虽然我也打算最终解决这个问题,但目前这基本上只是为了我和几个朋友的个人项目,我的大部分框架都是用PHP实现的。因此,如果可能的话,我想先在PHP中实现这一点,然后如果我决定让它更具可伸缩性,就考虑移植它
谢谢 你看过JavaScript的window.unload吗?@JayBlanchard我看过,但我的理解是它非常不可靠,而且跨浏览器兼容性不强,所以我希望找到一种方法来注册脚本服务器端的断开/停止。服务器也无法意识到有人离开或关闭了浏览器-他们完全没有权限断开的。我一直认为window.unload是合适的,并使用它来调用AJAX,以便服务器端脚本知道发生了事件。