Comet Discovery Series two "Ajax polling multiplexing Model"

Source: Internet
Author: User
Tags format message

Comet Discovery Series two "Ajax polling multiplexing Model"

write in front: Ajax polling believe that everyone is using, but there is such a problem, if a site at the same time there are a lot of places need to use this poll? Take our website, there is an unread message number reminder, there is a time to load the latest said, yesterday added a full network, and later will have a similar function to add is sure, do you want to create a separate polling for each function? Knowing that most of the polling requests are useless will cause a huge waste of server resources and broadband. Therefore, each additional polling point in the page, the pressure on the server and broadband waste will multiply. Consider another case, if the current Web page requires not only a simple Ajax polling, but Ajax long polling it? For example, in a Webim app to chat with two friends at the same time, is not to create a long poll for each friend? It's not scientific, it's unrealistic, and the HTTP1.1 protocol stipulates that the same client can only keep two connections with the server at the same time, and the problem becomes tricky. So think that all polling is nothing more than timing to the server to fetch messages, then we are not only set up a polling point to the server to pick up the message, and the server will be all the client needs of the message pack to be sent to the polling point one time, and then by the polling point of the returned messages to the point-to-order processing, the heartbeat Programmers speak in code.

<!--client code-->var rtmsg = {//Request address Uri:u ("public/rtmsg/rtmsg"),//The message to get, can be dynamically increased or decreased as needed, such as from template variable, so as to reduce unnecessary data waves             Fee Broadband Items: ' Unreadcount,allnet,newfeed ',//Establish connection connect:function () {$.ajax ({Url:rtmsg.uri,  data:{' Items ': Rtmsg.items}, type: ' Post ', DataType: ' JSON ', success:function (RES) {//After the request succeeds, the returned result is assigned to processing rtmsg by Hadnleres.            Handleres (Res.data); }})}, and//assigns the retrieved result to the corresponding handler handleres:function (res) {for (x in res) {eval (' rtmsg.        Handle ' + x + ' (res[x]); }},//Processing unread Messages Reminder Handleunreadcount:function (res) {/*............*/},//handling the entire network message handleallnet:function (allnet)     {/*............*/},//Latest deal handlenewfeed:function (newfeed) {/*............*/}/* I still want */* I can add * * };    $ (function () {//every 10 seconds setinterval (Rtmsg.connect, 10000); Page load finished first time rtmsg.connect ();})

<!--server-side program, note: I am using thinkphp framework--><?php/** * Real-time message push module */class rtmsgaction extends action{/** * Module Initialization *        /function _initialize () {//closed session, connection occupied session guide to page wait Session_write_close ();    Unlimited Request Timeout Set_time_limit (0);        The Public Function rtmsg () {//receives the message item to get $items = $_request[' items '];        Collect message $rt = $this->collect (Explode (', ', $items)); The returned message format is as large as the following $rt = Array (' Unreadcount ' =>array (' status ' =>1, ' data ' =>array (' Total ' =>5, ' system ' =>2, ' message ' =>3), ' allnet ' =>array (' status ' =>1, ' data ' =>array (' Message one ', ' message two ', ' message three ', ' data format custom, convenience client Handle as good '), ' Newfeed ' =>array (' status ' =>0, ' data ' =>false)//Return JSON format message echo Json_enco    De ($RT); }/** * Collects information that needs to be returned to the client */Public function collect ($items) {//sets what message is obtained by default when no items are passed $items = $i        TEMs $items: Array (' Unreadcount ', ' allnet ', ' newfeed '); $rt = ARray ();        Get message by Item foreach ($items as $v) {$rt [$v] = Call_user_func (Array (& $this, ' get '. $v));    } return $RT; /** * Gets the number of user notification statistics */Public Function Getunreadcount () {/* Get message procedure omitted, return information format as follows */$data [' Stat        US '] = ' Get information status ';        $data [' data '] = ' information details ';    return $data; }/** * Get the WHOLE network * * * Public Function getallnet () {/* Get message procedure omitted, return information format as follows */$data [' status '] = ' get        Information status ';        $data [' data '] = ' information details ';    return $data; }/** * Get the latest to say */Public Function getnewfeed () {/* Get message procedure omitted, return information format as follows */$data [' status '] = ' received        Information status ';        $data [' data '] = ' information details ';    return $data; }}

The key of the base real model is the classification collection of each message and the allocation processing after the return message, that is, the following two parts of the code

Client: Assigns the retrieved result to the corresponding handler handleres:function (res) {for    (x in res) {        eval (' Rtmsg. Handle ' + x + ' (res[x]);}    }

Server-side: Collect information by item foreach ($items as $v) {    $rt [$v] = Call_user_func (Array (& $this, ' get '. $v));}

At this point the Ajax polling multiplexing model is built, technology is not technical, the key is coincidence, and finally summed up the advantages and disadvantages of this model.

Advantages: It avoids the server resources and bandwidth waste caused by multiple polling points of clients, and can dynamically change the message items that need to be acquired for easy management.

Cons: There is no way to assign a separate request frequency for each point that needs polling, and in general it doesn't matter if the disadvantage is used in long polling and no longer exists.

Comet Discovery Series two "Ajax polling multiplexing Model"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.