以下是你可能会使用长轮询(使用jQuery和Yii的)一个样板:
服务器端:
class MessagesController extends CController {
public function actionPoll($sincePk, $userPk) {
while (true) {
$messages = Message::model()->findAll([
'condition' => '`t`.`userId` = :userPk AND `t`.`id` > :sincePk',
'order' => '`t`.`id` ASC',
'params' => [ ':userPk' => (int)$userPk, ':sincePk' => (int)$sincePk ],
]);
if ($messages) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array_map(function($message){
return array(
'pk' => $message->primaryKey,
'from' => $message->from,
'text' => $message->text,
/* and whatever more information you want to send */
);
}, $messages));
}
sleep(1);
}
}
}
客户端:
<?php
$userPk = 1;
$lastMessage = Messages::model()->findByAttributes([ 'userId' => $userId ], [ 'order' => 'id ASC' ]);
$lastPk = $lastMessage ? $lastMessage->primaryKey : 0;
?>
var poll = function(sincePk) {
$.get('/messages/poll?sincePk='+sincePk+'&userPk=<?=$userPk?>').then(function(data) {
// the request ended, parse messages and poll again
for (var i = 0;i < data.length;i++)
alert(data[i].from+': '+data[i].text);
poll(data ? data[i].pk : sincePk);
}, function(){
// a HTTP error occurred (probable a timeout), just repoll
poll(sincePk);
});
}
poll(<?=$lastPk?>);
记得要实现一些这种认证可以避免用户阅读其他消息。
调查websockets/AJAX轮询/长轮询。 – Matt