2

He there!

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

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.

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.

Thanks a lot.

1
  • 3
    Look into websockets/ AJAX polling/ long polling.
    – Matt
    Nov 4, 2013 at 15:09

1 Answer 1

1

Here's a boilerplate you might use for long polling (using jQuery and Yii):

Server-side:

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);
        }
    }

}

Client-side:

<?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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.