Implementation of comet in asp.net

Source: Internet
Author: User
Tags sendmsg

There are many introductions on "server push" on the Internet. One of the implementation methods is to use the comet technology to establish an http "persistent connection" between the browser and the server ", the so-called "persistent connection" means that the http request sent from the browser to the server will not receive a response from the server immediately, but when certain conditions are met, the server "takes the initiative" to return data to the browser. At this time, an http request is completed. For details about common http connections and http persistent connections, see:

Figure 1

For example, the left side is a normal http connection. After the server receives the http request from the browser, it will immediately respond. The right side is an http persistent connection. After the server receives the http request from the browser, if any data needs to be returned, return immediately. Otherwise, the server will "hold" the http request. That is, the server freezes the http request until the server has data to return to the browser or times out, the server "unfreeze" the http request. At this time, the http request "browser-> server" is complete.

The "persistent connection" function is obvious. It allows the server to "take the initiative" (note that double quotation marks are automatically added here) to send data to the browser. Yes, you have not heard the error, traditional Web programs can only send active requests from the browser to the server and then respond. Now, the server can "actively push" data to the browser. Since the server can "actively push" data to the browser, we can do a lot of things that we could not do before, for example, applications such as "instant messaging" and "Real-time Monitoring" that require real-time data update on clients. If the "active push" method is not adopted on the server side, we can actively loop requests to the server side Using ajax on the traditional Browser Side, to achieve the so-called "real-time" data update effect, such as ajax requests to the server every second to refresh the interface data, but the disadvantages of this method can be imagined, no matter whether the server has the data to be updated, browsers must repeatedly send requests (for more information about the disadvantages of ajax round-robin, see other articles on the Internet ).

The key to implementing comet is as follows:

1) The server will not immediately respond to the browser's http Request (unless there is data to be returned to the browser at the time );

2) After the browser processes the data returned by the server, it must immediately establish an "http persistent connection" for the next use;

3) when the browser processes the data returned by the server (before the next persistent connection is established), if the server needs to send new data to the browser, the server must save the new data, after the next "persistent connection" is established, it will be sent to the browser together;

4) to enable the server to actively push data to the browser in real time, the browser and the server must maintain an "http channel" (that is, http persistent connection) at all times ), the server can use this channel to return data to the browser;

5) as soon as the browser receives the data returned by the server, an "http persistent connection" is over and the next one needs to be re-established.

If we look at "http persistent connection" from the perspective of socket programming, it will be like this:

Figure 2

For example, each browser must always have an http downstream channel (Server> browser, as shown in figure (1). In this way, the server can "actively push" data to the browser at any time, each browser can initiate other normal http requests (in figure (2). In this way, browser 1 sends data (get/post) to the server through normal http requests, the server can immediately push the data to browser 2 (using the http downstream channel). That's right. Isn't that socket programming?

In asp.net, the asynchronous programming model (APM) can be used to implement comet. Specifically, the IHttpAsyncHandler interface and its BeginProcessRequest and EndProcessRequest methods are involved, when we receive an http persistent connection request from a browser, we only call IHttpAsyncHandler. the BeginProcessRequest method is asynchronous, because we do not call IHttpAsyncHandler immediately. the EndProcessRequest method, so the http request will not end immediately (that is, the request is frozen by the server). When the server has data, we use the Response method. the Write () method sends data to the browser and calls IHttpAsyncHandler. the EndProcessRequest method ends the asynchronous processing of http requests. At this time, the browser will receive the data "actively pushed" by the server. The request ends at this time. Then, the browser initiates an "http persistent connection" request again through the script and repeats in sequence.

At the end of the article, a demo of instant messaging is uploaded. Every logged-on user can send messages, online users can receive data pushed by the server (including online, offline, and message content) in a timely manner. Because the server sends a large number of data types, I simply specified a protocol, similar to the following:

1 Protocol is similar to the Protocol in socket communication programming (similar ): 2 [4 bytes] + [16 bytes] + [some] + [1 byte] 3 Message Type + message length + message content + verification bit 4 5 (Web Server-> Browser direction) each packet in json format is similar to the struct in C ++: 6 7 users are online: 8 {9 "type": "login", 10 "login_name": "xiaozhi_5638 ", 11 "login_time": "12:34:19" 12} 13 14 a user sent a message: 15 {16 "type": "sendmsg", 17 "msg": "hello world! [Emo: 23] ", 18" send_name ":" xiaozhi_5638 ", 19" send_time ":" 12:34:19 "20} 21 22 users go offline: 23 {24" type ": "logout", 25 "logout_name": "xiaozhi_5638", 26 "logout_time": "12:34:19" 27} 28 29 heartbeat packet: 30 {31 "type": "heartbeat ", 32 "time": "12:34:19" 33} 34 35 logon result: 36 {37 "type": "login_result", 38 "result": "true ", // or false39 "online_users": ["xiaozhi_5638", "somebody", "zhangsan"], // returns online after Successful Logon User 40 "time": "12:34:19" 41} 42 43 self-sent message result 44 {45 "type": "sendmsg_result", 46 "result": "true ", // or false47 "msg": "hello world! [Emo: 23] ", 48" time ":" 12:34:19 "49} 50 51 data packet set (the preceding data packet is a single data packet, and data_list contains multiple data packet sets) it is used to transmit data packets cached by the server to browser52 {53 "type": "data_list", 54 "list": [{"type": "login", "login_name ": "xiaozhi_5638", "login_time": "12:34:19" },{ "type": "sendmsg", "msg": "hello world! "," Send_name ":" xiaozhi_5638 "," send_time ": "12:34:19"}] // The array type contains multiple packets 55} 56 Browser-> data transmitted to the Web Server in normal get/post ModeView Code

Data from the server to the browser is transmitted in json format, and the browser to the server uses the ajax library written by jquery. The browser script only needs to parse the json data transmitted by the server, update the interface, and then initiate the next "http persistent connection" request. The code for initiating an http persistent connection using a js script is as follows:

1 function Open_Http_Channel () // enable an http channel (http persistent connection) 2 {3 $. ajax (4 {5 url: "chat_aspx.ashx", // action processing page 6 type: "post", // data transmission method 7 data: {"requestType": "a_long_connection ", "id": $ ("# input_user_name "). val ()}, // upload parameter 8 dataType: "json", // return data type 9 success: function (data) // parse the returned json package 10 {11 // receive the data returned by the web server and start parsing the data. See protocol.txt 12 if (data. type = "login") // someone goes online 13 {14 ShowLogin (data); // display login information 15} 16 if (data. type = "sendmsg") // someone sends the message 17 {18 ShowMsg (data. msg, data. send_time, data. send_name); // Display message 19} 20 if (data. type = "logout") // someone offline 21 {22 Logout (data); 23} 24 if (data. type = "data_list") // data packet set 25 {26 for (I in data. list) // traverses the packet set 27 {28 if (data. list [I]. type = "login") 29 {30 ShowLogin (data. list [I]); // display logon information 31} 32 if (data. list [I]. type = "sendmsg") 33 {34 ShowMsg (data. list [I]. msg, data. list [I]. send_time, data. list [I]. send_name); // Display message 35} 36 if (data. list [I]. type = "logout") // deprecate 37 {38 Logout (data. list [I]); 39} 40 //... 41} 42} 43 //... 44 //... 45 //... other protocols defined here parse 46 Open_Http_Channel (); // immediately enable the second http channel 47}, 48 error: function (xhr, info, obj) 49 {50 Open_Http_Channel (); // enable the second http channel 51} 52}); 53}View Code

For more details, see source code. Figure 3 (gif emojis are not resolved and replaced, directly displayed in text)

Figure 3

Source Code address: http://files.cnblogs.com/xiaozhi_5638/comet_in_aspnet.rar vs2008

Jquery and several interface libraries related to it are used. Do not log on to too many users in the same browser, because the browser will maintain an http connection for each user, the browser has a limit on the number of http requests (the maximum number of chrome requests used by the author is 6). If the limit is exceeded, all http requests will be blocked.

Related Article

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.