Asp.net build scalable comet Web applications (2)

Source: Internet
Author: User

Description

If you have read one of my previous articlesArticleAsp.net: building scalable comet web applications. You should be able to understand what I will write. I explained the comet technology and explained how to use Asp.net to build scalable applications. However, I think the previous article is a bit like the main line. It demonstrates enough technology, but not enough to include any usefulCode. Therefore, I think I need to write an API to encapsulate the functions in the previous article. Encapsulated into a series of neat classes that can be included in a common web project, giving you the opportunity to expand and test it.

I will not cover much details about the thread model. Because the previous article involves too much content about it. I will only explain how APIs are involved in your web application.Program.

I decided to write a lightweight message sending API, which is similar to bayeuxprotocol [Bayeux is a protocol that provides low latency and transmission of asynchronous messages (mainly based on HTTP) between the Web server and the web server)] information exchange method. However, it does not have a protocol-based implementation. If I believe it can be overdone, it is needed to work with these Apis. And it is just a draft.

In my original article, I will give a small game. Unfortunately, I think it may be easier to use a simple chat program. This program uses a comet channel to receive information and uses a WCF Service to send information.

Basic chat program:

Glossary

The following is a list used in my article and their descriptions.

Channel: This is the end point that a comet client can connect. Any information sent to the client must be transferred to the channel for transmission.

Timeout: When a client has been connected to a channel and has passed the pre-defined period of time, it has not received any messages. When timeout occurs, the client can establish a new connection.

Idle Client: This is the time limit when a client is not connected to the server. An idle client will be disconnected after a preset time.

Message: A message in JSON format sent to a client through a channel.

Subscription: A client is subscribed to a channel. They are connected and ready to accept messages.

Project code

The project code contains all the comet classes that can be used in your Asp.net project. The code is very similar to the Code designed in the original article. However, I have extended the function to transfer common messages on the client and server.

The main class for controlling comet is cometstatemanager. This class manages a single channel. This class uses an instance of the icometstateprovider interface to manage the status of your application in a special way. There is a built-in inproccometstateprovider implementation in the API to store the status in the server's memory. Obviously, this is not a good practice for implementing the load balancing environment. However, you can implement a custom provider to use a database or a custom status server.

To expose your channel to the outside, you need to wrap it with an ihttpasynchandler implementation. I finally tried to use a WCF asynchronous model. However, it is found that it will not release Asp.net working threads, just like using asynchronous handler. This is a pity, but it is not expected.

The following code shows how to create an ihttpasynchandler to provide an end point for your comet channel.

The above code is simple enough. We have a cometstatemanager class static instance. It is used to build an instance of icometstateprovider. In this example, we use the built-in inproccometstateprovider implementation.

The rest of the implementation of this class is to map the beginprocessrequest and endprocessrequest methods to the beginsubscribe and endsubscribe methods of the cometstatemanager class instance. We also need to configure handler in Web. config to use it.

This channel can now be subscribed by the client

Cometclient class

The channel must be connected to the client. Each client represents a cache sorted by a cometclient instance. We do not want any old client to connect to the server or any unauthenticated client registration channel. Therefore, we hope to implement an authorization and authentication mechanism. It may be Asp.net standard form authentication, or maybe a WCF calls a service to verify creden。 and instantiate a client in our channel.

The following code shows the logon operation on the default. aspx page:

We didn't verify the password or anything else. We just entered the user name on the page and used it to distinguish different clients. A comet client has two tokens for API use:

PrivatetokenThis token is private to the client and is used to register messages to the client.

PublictokenThis token is used to identify which client is used. It is usually used when a message is sent to a special client.

The reason we use a public token and a private token is that the private token can be used to register a channel and receive messages from other users. We do not want any other client to isolate the original client (for example, we do not want message spoofing ). For this reason, if we want to send messages between two clients, we use a public token.

For simplicity, I have included a displayname attribute on the client to store the user name.

To create a channel on the client, you need to call initializeclient. It is displayed on it. This method carries the following parameters:

Publictoken-Client public token

Privatetoken-Client Private token

Displayname-Client display name

Connectiontimeoutseconds-Connection timeout

Connectionidleseconds-The number of seconds to wait for a client to reconnect after killing idle clients on the server.

In the above example,InitializeclientYes. Specify the user name as the public token, private token, and display name from the form. This is not very secure, but it is sufficient for a demo. To make it more secure, I could have produced a guid as a private token. And use the public token as the user name.

InitializeclientIt will be called through icometstateprovider. A new initializeclient instantiates the cometclient class. It is expected to be stored in the cache.

WithCometclientClients can use their own private tokens to subscribe to channels.

Client Javascript

To implement client functions, there is a file in the project,Scripts/aspnetcomet. jsContains all the JS (and public JSON converter) that need to be subscribed ). To make everything easier, I included a static method in cometstatemanager to callRegisteraspnetcometscripts. It accepts a page with parameters and registers scripts on the page.

As it is called, we are free to use the client APIs that we can use. The following example is taken from chat. aspx in the project. It also shows how to subscribe to a common channel once a client is instantiated.

All functions of the client API are encapsulated into a javascript class called aspnetcomet. An instance of this class is used to track the status of a connected client. It is required to subscribe to the handler URL of the comet end. The private token of the cometclient and an alias are used to differentiate the client channel. Once we build an aspnetcomet instance, we can define a series of handler in the comet lifecycle for calling at special times.

Addtimeouthandler-When a client waits for a scheduled event and does not receive a message, call the handler.

Addfailurehandler-When a comet call fails, one of the failure examples is that the comet client is not connected and the handler is called.

Addsuccesshandler-Handler is called when each message is sent to the client.

The following code shows the signature of each handler method:

SuccesshandlerIs an instance of the cometmessage class. The following code shows the class and its JSON format:


Send a message

In this chat application, I have included a WCF web service that can use ajax to play the end point of the message sending function. The following code shows the processor of the client event that clicks the send message button:

This Code creates an object created by the Asp.net Web Service Framework.ChatserviceThe instance of the client object. Then, only the sendmessage method is called to pass the private token and message of the client.

SendmessageThe Code carries parameters and writes a message to all clients. The following code shows the functions:


This method searches for cometclient from the private token and creates a chatmessage object used as the message content. The message content is sent to each connected client through the sendmessage method of the instance of cometstatemessager. It will penalize any connected client for returning the successhandler method included in the chat. ASPX page. It writes information to the chat area of the page.

Use this code

When executing the website in the solution, you do not need to change any configuration, just connect some clients to the application. And the chat information should be sent in real time.

Using this API will enable you to use a comet style solution in your Ajax program. Using WCF enables you to send messages to the server, which have been automatically packaged for you. Then, you only need to call back in a comet channel to connect to the client.

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.