ASP.NET development chat room program (English)

zhaozj2021-02-08  491

Introduction:

In its new avatar, ASP has undergone a metamorphosis. It is no longer confined to simple server-side scripting. It is no more mere bits of HTML contents or data inserted into template HTML code. With it, you can create a full-fledged Web Application, On The Fly, with Control Over Several Critical Factors.

Anyway, you may ask, what is the difference between a web application and a web page? In server side scripting your role is limited to, and ends with, the rendering of the web page on the client's browser, save that, you can maintain some control over the session and session related variables On the other hand, for a web application, you approach the whole affair differently -.. the server is where the action takes place and the page is no longer a simple HTML document Instead, the web page is a frame on which you create an interactive session between you and the client or between clients among themselves. you compose it from scratch placing elements at the appropriate places, wiring up event handling, storing variables not only for the session state but also for .

The Last Mentioned Ability Makes An ASP.NET Application Into a Peer 2 Peer Networked Application. This Article Will Present You with one claim peer 2 peer networked Application In the form of a chat application.

Charting the course for catch

How do you create a Chat Application Traditionally, for a chat application, you have to create aserver side listener, which requires a server side TCP / IP channel and listens for requests from clients These requests can be of two types?.:

Registering a new chat participant Passing on chat messages to other chat participants.In addition, the server-side program gets a handle to the client object and uses this handle to update chat messages of the participants as well as the list of participants at any given Time.

However, in this ASP.NET application, the problem of the Server-side listener can be side stepped, as ASP.NET itself will be the listener. Thus there is no hogging of a TCP / IP channel for a dedicated listener.Since an ASP.NET Application uses the HTTP Protocol and the corresponding Port 80, it is not affected by most of the firewalls, unlike a dedicated chat listener. TheHttpApplicationState State Object, provided to us by the NET Framework, solves the problem of sharing Information Across Applications. The Options Available To US in This Regard Are:

The ttpapplicationState Object, The System.Web.caching.cache Object, Database Back end The isolated storage dump.

Whilst the last two options involve Read / Write / IO operations, they are not suitable for a simple chat application where the speed is the essence and there is no great amount of memory involved. The cache object does not provide for locking and may affect synchronization when several users access the page at the same time. Hence, we zero in on theHttpApplicationState object for our data storage. Finally we handle the trickiest question of pushing messages from the server to the client using the web services behavior of Internet Explorer 5.0 And Above

. - On the server.

Thus, we can summarize our course of action as follows: Design aChatMessage Object and create a placeholder for these objects at the Application Level (Why do we do this at the Application 'Level - ASP.NET enables us to keep variables.? . at the Application level as well as at the Session level However, the session level variables can not be shared between sessions unlike the Application level variables Therefore, we pitch for the Application variables) Create a web service which provides three methods -.. one for registering a participant, one for exchanging messages with him and one for merely supplying the waiting messages at the askance! Design a client web page that uses DHTML behavior known as webservice behavior given to us by Microsoft as webservice.htc. Componentise the client side code - SO That Web Developers NEED NOT KNOW The Intricacies of use Web Services, XML, XMLHTTP AND DHTML Behaviors, in Order To Use The Application We Made.

Creating the WebService:

As mentioned earlier, in a Peer to Peer application, the server support is needed for three actions - registering the peers, receiving messages for routing and passing on waiting messages Therefore, our web service will have three Web Methods:.

Public String Registermember (String Nickname) Public ChatMessage XchangeMsgs (String Nickname, String MSG) Public ChatMessage GetMsgs (String Nickname)

The web service is encapsulated in a class called ChatWebService, which is derived from System.Web.Servicesand is contained in the source code fileChatWebService.cs in the namespace PrasadWeb. The namespace also defines two other classes calledMember and ChatMessage . The classMessage has a string variable called UserName, a DateTime variable calledLastAccessTime and a public property NickName, which gets and sets the variableUserName together with the time of his registration. The ClassChatMessage has merely two string variables called UserList and messages. These two variables hold formatted lists of Chat Participants and the undelivered chat messages at any given time.The main classChatWebService has two private methodsString GetMemberList () and Void CheckMemberList (), besides the three Web Methods mentioned Earlier. The Former Function Returns The List of Chat Participants At Any Given Time As a formatted list. The later function checks to see reason Sent from The Circuit for more Than 2 Minutes and Removes Him from The chat list, so as to keep the environment free from quitters. The getmemberlist function Works as Follows:

Public String getmemberslist ()

 

//WE NEED to LOCK The App to Enable Syncronization

 

/// The variable for the return message

String UserList = ""

// Every Web Application Has An Application Property

// Which Yields a Handle to The ApplicationState Object.

// ApplicationState Object Stores The Collection of

//MEMBER Objects (WE WILL SEE LATTER HOW WE DO IT).

// We Obtain an array of the keys to the collection

// and store the array in a variable 'members'

String [] MEMBERS = Application.AllKeys;

// We can now unlock the Application

 

Application.unlock ();

 

// Now we read the username variable in Each MEMBER

/// Object Found in The HttpApplicationState State Collection

// and store these values ​​in a string Separated by

// newline character

201 (int x = 0; x

As the application involves multiple users - all accessing the same set of variables stored by us in the application object - we need to use Code Synchronization by invoking theLock andUnLock methods of theSystem.Web.HttpApplicationState State object whenever a write Operation is performed by US.

In theRegisterMember method, we first check if the username supplied by the client is unique - if not, reject the name Then, we instantiate a newMember object for the new participant and add the object to theApplicationState objects collection.. We do these with the folowing code:

Public String Registermember (String Nickname)

{{

Checkmemberslist ();

String [] MEMBERS = Application.AllKeys;

                                     

{

THROW New Exception ("UserName Already Exists.

Please Select Another Name ");

}

MEMBER NEWMEMBER = New Member (Nickname);

Application.lock ();

  Application.Add (Nickname, NewMember);

Application.unlock ();

Return Getmemberslist ();

}

Again, All these is versions.

Whenever a client sends a message through theXchangeMsgs method, we first call theCheckMembers private method to update the list of chat participants in our collection. Then we check if the just received message carries a familiar Nick Name that is already registered with us . Then we loop through all theMember objects in our collection, open each of them and insert the just received message into theMessages variable of each of theseMember objects -. after due HTML Formatting Finally, we retrieve theMessages string stored in theMember object corresponding to the current client caller as the return value and empty theMessages variable of that object.TheGetMsgs web method is similar to the above except that this method does not being us any new messages from the client And it is merely caled to collect all the pending message and the current list of chat part participants.

Creating the chat client:

Our Chat Client is an HTML Web Page, which contains a table with 7 rows and one column. The first row contains the name of the Chat Application. The even numbered rows bear the captions and row number three contains the Chat Participants List whilst row five Is for chat messages. The Last Row Has A Text Box and a Submit Button. Rows Three and Five House A

EEEEMENT WITHIN THEM, WHOSE

Scroll Property Has Been Set TO

Auto.

Attaching The Webservice Behavior:

The Table Webservice Behavior Defined in The Webservice_Ver1.htc File, As Follows:

The page has two script blocks of which one is invoked on theonLoad event of the window This script block calls the use method of the webservice behavior by passing the URI of the webservice as a parameter as follows:.