Yiiframework消息弹出弹出、消息、Yiiframework

2023-09-10 19:50:16 作者:穿着校服逛酒吧°

他那里!

如果有涉及到两个不同的问题,我目前在我工作的一个应用程序的问题。

If have a question that is related to two different issues I currently have in an application I'm working on.

问题1: - 有一条信息系统。用户可以相互发送消息。我想有一个实时弹出当用户得到一个新的消息,而不是收件箱页面上。

Issue 1: - There is a message system. Users are able to send each other messages. I would like to have a real time pop up when the user gets a new message and is not on the inbox page.

问题2: - 我想创建一个基本的成就系统,成就人们可以(例如)是:接收的消息。

Issue 2: - I would like to create a basic achievement system, one of the achievements could (for example) be: "Receive a message."

现在,我认为这两个功能可以通过相同的方式来实现。你们任何人有这种类型的实时通信的经验吗?我真的不知道从哪里开始。我真的很喜欢它,如果它不重。

Now I think both functionalities can be achieved through the same way. Anyone of you has any experience with this type of real time communication? I really have no idea where to start. I would really love it if it is not to heavy.

非常感谢。

推荐答案

下面是你可能会使用长轮询(使用jQuery和Yii的)一个样板:

Here's a boilerplate you might use for long polling (using jQuery and 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?>);

记住要执行某种身份验证,以避免用户的阅读其他人的消息。

Remember to implement some kind of authentication to avoid users reading each others messages.