我看到有一个问题,但我不知道如何在我的情况下实现它(因为我没有使用多个会话)。此外,我必须说长轮询本身是有效的,但在它运行时别无其他。
有javascript文件设置方法,chat.php文件在此基础上接收消息(开始轮询)或发送它们。问题是,如果我包含“while”功能,我就无法发送消息。这是:
来自chat.js的:
chat.fetchMessages = function ()
{
if(localStorage.getItem("amInQueue") != 1)
{
$.ajax({
url: '../ajax/chat.php',
type: 'post',
data: { method: 'fetch' },
async: true,
cache: false,
timeout: 50000,
success: function(data)
{
if(data!='')
{
chat.printMessages(data);
}
setTimeout(chat.fetchMessages, 1000);
}
});
}
}
chat.throwMessage = function (message, byuser)
{
if ($.trim(message).length != 0 && localStorage.getItem("amInQueue") != 1)
{
$.ajax({
url: '../ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message, byuser:byuser },
success: function(data)
{
chat.entry.val('');
}
});
}
}
来自chat.php:
<?php
require '../core/init.php';
if (isset($_POST['method']) === true && empty($_POST['method']) === false)
{
$chat = new Chat();
$method = trim($_POST['method']);
if($method === 'fetch' && $_SESSION['ses_amInQueue']==0)
{
$shouldStop=0;
$messageIDs = $chat->checkForLatestMessage($_SESSION['ses_myChat'], $_SESSION['ses_meInChat']);
while($messageIDs=='')
{
usleep(30000);
clearstatcache();
$messageIDs = $chat->checkForLatestMessage($_SESSION['ses_myChat'], $_SESSION['ses_meInChat']);
}
if($messageIDs!='')
{
$messageString=$chat->getNewMessages($_SESSION['ses_myChat'], $messageIDs);
$chat->deleteMessages($messageIDs);
echo $messageString;
}
}
else if($method === 'throw' && isset($_POST['message']) === true)
{
$message = trim($_POST['message']);
$byuser = trim($_POST['byuser']);
if (empty($message) === false)
{
$chat->throwMessage($byuser, $message, $_SESSION['ses_otherInChat'], $_SESSION['ses_myChat']);
}
}
“while”循环运行时,我无法使用“throw”方法。我尝试在“while”循环结束时检查方法以查看它是否“抛出”并将其包含在“while”的条件中,但由于某种原因这不起作用。
如何解决这个问题?两者都独立工作,或者如果我删除“while”循环(但它不再是长轮询)。