Asp.net step-by-step processing: a simple web chat like QQ Asp.net asynchronous Processing Mechanism Research a simple implementation of ASP. Net-based comet

Source: Internet
Author: User

I have initially studied the Asp.net step-by-step processing model four months ago and wrote a learning summary: Asp.net asynchronous Processing Mechanism Research, because there has been no chance of application, it will soon be left behind. A friend said that he needed a web chat tool similar to QQ chat. I immediately thought of it. After several hours of fighting, I finally made a simple chat demo, as shown below:

 

The left and right figures represent the two browser interfaces opened separately. When a user on the right selects an online user and enters and sends the information in the input frame, the user on the Left can immediately receive the information.

I. Summary

1. Front-end

Front-endCodeThe most important function in wait is as follows:

 Function wait () {$. Post (  "  Sendhandler. ashx? Ran =  " + New Date (). gettime (),{ " Senderid  " : $ ( "  # Hdcurrentuserid  "  ). Val ()}, function (result ){  If  (Result. Content) {$ (  "  # Divcontent  " ). Append ( "  <Div>  " + Result. Sender. Name + " Said:  " + Result. content + "  </Div>  "  )}  If  (Result. List) {refreshonlinemember (result. List, $ (  "  # Hdcurrentuserid  "  ). Val ();} Wait ();})} 

At a glance, this is a recursive function. After sending a request to the server, it is always in the connection state. When the server responds, It updates the interface information with the returned information and calls itself again.

2. Background

Public Iasyncresult beginprocessrequest (httpcontext context, asynccallback CB, Object  Extradata) {messageasyncresult result = New  Messageasyncresult (context, CB );  If ( String . Isnullorempty (context. Request. Params [ "  Receiverid  "  ]) {Messagecenter. Active (  New GUID (context. Request. Params ["  Senderid  "  ]), Result );}  Else  {Messagecenter. sendmessage (  New GUID (context. Request. Params [ "  Senderid  " ]), New GUID (context. Request. Params [ "  Receiverid  " ]), Context. Request. Params ["  Content  "  ], Result );}  Return  Result ;}  Public   Void  Endprocessrequest (iasyncresult result) {messageasyncresult messageresult = Result As  Messageasyncresult; messageresult. httpcontext. response. contenttype = "  Application/JSON  " ; Messageresult. httpcontext. response. Write (jsonconvert. serializeobject (  New {Sender = messageresult. Sender, content = messageresult. Content, list = Messagecenter. getonlinemember ()}));} 

The background code is strictly written in accordance with the asynchronous model, implements the ihttpasynchandler interface, calls the relevant processing functions in the begin function, and returns information to the client in the end function.

3. Callback object

 Public   Class  Messageasyncresult: iasyncresult {  //  + Static part  //  Static internal class area //  Static Field Area  //  Static attribute Area  //  Static constructor area, sorted by parameters from few to multiple  //  Static Method Area  //  + Dynamic part  //  Dynamic internal class area  //  Dynamic field area      Private   Bool _ Iscomplete =False  ;  Private  Asynccallback _ asynccallback;  //  Dynamic attribute Area      Public Member sender { Get ; Private   Set  ;}  Public Httpcontext { Get ; Set  ;} Public   String Content { Get ; Set  ;}  //  Dynamic constructor area, sorted by parameters from few to multiple      Public  Messageasyncresult (httpcontext context, asynccallback) {httpcontext = Context; _ asynccallback = Asynccallback ;}  //  Dynamic Method Area //  -This method Area      Public   Void Sendmessage (member sender, String  Content) {sender = Sender; Content = Content; _ iscomplete = True  ;  If (_ Asynccallback! = Null  ) {_ Asynccallback ( This  );}}  //  -Rewrite the base class method area and trace back to the Object layer by layer from the direct superclass.  //  -Rewrite the Interface Method Area and implement it in sequence according to the order in which it appears.      # Region Iasyncresult Public   Object  Asyncstate {  Get { Return   Null  ;}}  Public System. Threading. waithandle asyncwaithandle {  Get { Return   Null  ;}}  Public   Bool  Completedsynchronously {  Get { Return   False  ;}}  Public   Bool  Iscompleted { Get { Return  _ Iscomplete ;}}  # Endregion      //  + Structure  //  Structure Method Area }

There is no new idea in writing this function. It plays two roles: 1. It serves as an intermediary to pass objects, such as httpcontext and member, and 2. It calls asynccallback to trigger the end event.

4. ProcessingProgram

 Private   Static Dictionary <guid, messageasyncresult> _ members = New Dictionary <guid, messageasyncresult> ();  Public   Static   Void  Active (guid ID, messageasyncresult result) {datasource. members. Find (M => M. ID = ID). lastactivetime = Datetime. Now; datasource. members. Find (M => M. ID = ID). islogin = True  ; _ Members [ID] = Result ;}  Public   Static   Void Sendmessage (guid senderid, guid receiverid, String  Message, messageasyncresult result) {datasource. members. Find (M => M. ID = senderid). lastactivetime = Datetime. Now; datasource. members. Find (M => M. ID = senderid). islogin = True  ;  If  (_ Members. Keys. Contains (receiverid) {_ members [senderid]. sendmessage (datasource. members. Find (M => M. ID = senderid ), String  . Empty); Result. sendmessage (datasource. members. Find (M => M. ID = senderid ),String  . Empty); _ members [receiverid]. sendmessage (datasource. members. Find (M => M. ID = Senderid), message );}} 

There is a _ member object that stores the key-value pairs between the user and the callback object. There are two other methods to activate the logon status and send information.

Ii. Ideas and key points

To understand the meaning of the above Code and the meaning described below, you must understand Asp.net's asynchronous processing model.

1. Client restrictions

First, user a logs on to the server. Here, the server has an httpapplication object serving it and generates an iasyncresult object, which includes an asynccallback delegate object. We are short for HA1, ra1, and cache objects. B users log on to Alibaba Cloud and serve a series of objects, such as Hb1, rb1. CB1 objects. In this case, object B sends a message to object A. When object B clicks the send button, a new request is sent to the server. Note that this is a new request, so there will be a new httpapplication object serving it, I call it hb2 object, generate a new iasyncresult object, I call it Rb2 object, however, the asynccallback delegate object is still the original one.

Then, use the key-value pairs in the cache to find the HA1, ra1, and cache objects corresponding to user a, locate the cache objects in user A, and execute them. The information is sent back to the client. After processing, a new request is automatically sent. Then, a new ha2, ra2, and C2.

Based on the above description, you can find out when the server responds, and when someone sends a message to you.

Currently, user B has two groups of services: Hb1, Rb1, CB1, hb2, Rb2, and cb1. Now there are two options: Keep it, actively return to the client, and then re-establish the client. My first confusion came from this. If you select the first scheme, you can imagine that if B keeps sending messages and never receives information, the server will have more and more HB *, AND THE Rb * object will be occupied by it rather than released. When I write the code, I first considered the first solution, and I found a strange problem. After B's ie sends messages nine times or FF sends messages five times in a row, the server will no longer receive messages from B. I couldn't find the cause before. Later I thought, would this be the limit on the number of concurrent connections in a single domain on the client? Because if the server object is occupied and no result is returned, the request is incomplete on the client. Because a request is automatically initiated when the page is loaded, ie is 10 times, FF is 6 times, which is in line with the default value of the number of concurrent connections. For example:

As you can see, when "5" is said in the left figure, the browser has 6 unreturned connections, reaching the maximum number of connections in a single domain. At this time, if you try again, the browser and the server will not respond.

2. Improved communication model

Select the second solution mentioned above. Now I will sort out my ideas again. User A establishes a connection to generate HA1, ra1, and cache objects. User B establishes a connection to generate Hb1, Rb1, and CB1 objects. User B sends information to user a to generate hb2, Rb2, CB1 object. At this time, there are two events to be done. The first ra1 object is called, the cache object is executed, and the end method of the HA1 object is called back to send information to the client. The request is processed completely. After receiving the information for processing, client a re-initiates the request to generate ha2, ra2, AND Ca 2 objects. Second, execute the newly created hb2, Rb2, and CB1 objects. Specifically, the Rb2 object is called, The CB1 object is executed, and the end method of the hb2 object is called back to send information to the client, end this request and run the previous Hb1, Rb1, and CB1 objects. Specifically, the Rb1 object is called, The CB1 object is executed, and the end method of the Hb1 object is called back to send information to the client, after client B receives the information for processing, it re-initiates the request to generate Hb3, Rb3, and CB2 objects. For example

The above demonstrates that a and B log on successively, and B sends two messages to a consecutively. There are three interactions in total. The curved arrow expresses the correspondence between requests and responses, and the black arrow expresses the trigger relationship between users. In this way, all users and servers maintain only one connection for most of the time.

The above explanation also explains why the code should be executed separately in ASP. Net-based comet simple implementation.

 
Asyncresult. Send (Null);

Let's take a look at the specific programming methods on the client.

 $ (Function () {$. Post (  " Loginhandler. ashx  " , Null  , Function (result ){  If  (Result. User) {$ (  "  # Spancurrentuser  "  ). Text (result. User. Name); $ (  "  # Hdcurrentuserid  " ). Val (result. user. ID); refreshonlinemember (result. list, result. user. ID); wait () ;}})}) function sendmessage () {$. post (  "  Sendhandler. ashx? Ran =  " + New Date (). gettime (),{ "  Senderid  " : Senderid, "  Receiverid  " : Receiverid, "  Content "  : Content});} function wait () {$. Post (  "  Sendhandler. ashx? Ran =  " + New Date (). gettime (),{ "  Senderid  " : $ ( "  # Hdcurrentuserid  "  ). Val ()}, function (result ){  If (Result. Content) {$ (  "  # Divcontent  " ). Append ( "  <Div>  " + Result. Sender. Name + "  Said:  " + Result. content + "  </Div>  "  )}  If (Result. List) {refreshonlinemember (result. List, $ (  "  # Hdcurrentuserid  "  ). Val ();} Wait ();})} 

You can see that the wait method is executed after the logon is successful. The biggest feature of this method is that after the callback is complete, it calls itself to initiate a new request. After the page is loaded, user a and user B will log on automatically. After the page is successfully loaded, each of them enters the wait method and waits for callback.

User B sends a message to user A, that is, a new request is sent when the wait callback is not waited. At this time, user a has one connection and user B has two connections, the sendmessage method is called. The biggest feature of this method is that there is no callback, that is, when the server returns, no new request is automatically initiated. In this way, you will understand. User A's unique connection is initiated by wait. After user B triggers the server to return a request, a new request is automatically initiated. User B has two connections. One is initiated by the wait method, and the server will re-establish the request upon return. The other is initiated by the sendmessage method, which ends after the server returns. In this way, user a and user B have one connection to the server most of the time.

3. Legacy issues

(1). Concurrency Problems

If B sends a message to a, the server receives the new message to a between the end a request and the new a request, and the information will be lost, or the callback object corresponding to a does not exist, and an exception occurs on the server. The more secure way is to allow the database to complete most of the functions, but to make the asynchronous programming model complete the Real-Time messaging, and access the database with the latest information each request.

(2). Connection timeout

Obviously, the connection of any browser is not waiting without a limited time. At this time, the server should record the last active time and regularly check all connection requests. If the time exceeds a certain period of time, such as 1 minute, the request is returned to the client and re-created.

(3). deprecate

This is similar to the principle of connection timeout. When a request is returned to the client and the client has not created a new request, it can be considered offline.

4. Function Enhancement

This is basically done with QQ, such as group sending and stealth. It is not too difficult to expand on the basis of the above

3. Highlights

1. Extended request types under iis7.5

The example of ASP. Net-based comet simple implementation can run normally in Vs, but it does not work in IIS and reports Error 404. The reason is that the author sets the path extension for request processing. asyn, but this file does not actually exist, Web. the httphandlers configuration section in conbfig maps the configuration to the custom class and does not work. In the classic mode of iis7.5, You need to configure the handler ings module in IIS separately so that IIS can process requests with this extension for Asp.net, rather than simply returning a 404 error. Specifically, add a script ing. The processing extension is. Asyn and the processing program is aspnet_isapi.dll.

2. Mount the Asp.net 4.0 website under iis7.5

Iis7.5 may not be able to process 4.0 websites by default. In the handler mappings module, if there is no 4.0 handler, the internal error 4.0 Server will be returned when a 500 website is mounted and requested. This problem may occur if IIS opened after vs2010 is installed first. The solution is to manually register the IIS 4.0 environment and run the following command in the command line.

 
% Windir % \ Microsoft.Net\ Framework \ v4.0.30319 \ aspnet_regiis.exe-I

4.Source code

Portal

ReferenceArticle

Asp.net asynchronous Processing Mechanism

Simple implementation of ASP. Net-based comet

How to debug the. Net 4.0 website with the default 500 Error in iis7.5 of win7 flagship Edition

Iis7 Asp.net URL rewriting Configuration

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.