Asp. Net creates Ajax-based chat room programs

Source: Internet
Author: User

Original Author Dahan Abdo
Translated from CodeProject

To download the source code, go to the original address:

My first chat room was written in ASP 3.0. The program is relatively simple. Two text boxes are used to process information refreshed every second on the page. At that time, to build a real chat room, you need to use Java Applet or ActiveX control. HTTP-based chart room faces the same problems as my first chat room. These problems include screen flickering caused by PAGE refreshing. However, this problem has been solved by AJAX. AJAX is a combination of JavaScript and XML asynchronous calls. Now we can use some JavaScript code on the server to implement a real chat room. This article does not introduce Ajax, and assumes that you have a certain understanding of the use of Ajax and ASP. NET. It only describes how to use Ajax technology to create a basic chat room.


This is a single chat room for multiple users. You can implement basic chat functions. You can also use command lines such as/admin clear to clear chat records and/nick [Name] To Change User nicknames. Program Description: This program uses a ChatEngine class to process all chat information and user information. User information is stored in a Hashtable, and chat information is stored in StringCollection.

Hashtable users;
StringCollection chat;
In Global. asax. cs, declare a Global ChatEngine instance, which is shared by all users in the chat room:

Public static UChat. ChatEngine. IChatEngine Engine = new UChat. ChatEngine. ChatEngine ();

Another JavaScript timer function is used to synchronize global variables and page information.

Function setTimers ()
TimeID = window. setTimeout ("updateAll ()", refreshRate );
Each user is uniquely identified by a username and a GUID.

Public void AddUser (string id, string user)
// Make sure user name does not exist already
If (! UserExists (user ))
// Add user to users list
Users. Add (id, user );

// Display a notification message to all users
Chat. Add (this. MakeServerMessage (string. Format (
Joinedfmt, user )));

Program running interface

The start page displays basic information about the current session, such as the user number and chat record size. You must provide a user name to access the chat room. Click Login button to enter the following functions:

Protected void Login (object sender, EventArgs e)
String user = txtUsername. Text;

If (! ValidateNick (user) return;

If (Global. Engine. UserExists (user ))
LblErrorMsg. Text = "A user with this"
"Name already exists, try again .";
Response. Redirect ("Server. aspx? Action = Login & u = "user );
After some simple verification, add the user to the user lists through the AddUser function, and then enter the chat room page chat. aspx. Then the following JavaScript function will be executed:

<Script type = "text/javascript">
SniffBrowserType ();
// Shows loading .. screen
ShowLoadScreen ();
// Set the javascript timer and
// Loads user list and messages
SetTimers ();
SetFocus (mytext );
When you type some information and press enter, the following function is called:

<Input type = "text" class = "mytext"
Id = "mytext" onkeydown = "captureReturn (event)">

// Capture the enter key on the input box and post message
Function captureReturn (event)
If (event. which | event. keyCode)
If (event. which = 13) | (event. keyCode = 13 ))
PostText ();
Return false;
Else {
Return true;
Function postText ()
// Clear text box first
Chatbox = getElement ("mytext ");
Chat = chatbox. value;
Chatbox. value = "";

// Get user GUID from url
Userid = location. search. substring (1, location. search. length );

// Construct Ajax Server URL
Url = Server. aspx? Action = PostMsg & u = userid & t =
EncodeURIComponent (chat) & session = rnd;

// Create and set the instance
// Of appropriate XMLHTTP Request object
Req = getAjax ();

// Update page with new message
Req. onreadystatechange = function (){

If (req. readyState = 4 & req. status = 200 ){
UpdateAll ();

Req. open (GET, url, true );
Req. send (null );
So much, nothing special, you can look at the source code, there is a lot of comment information.

Conclusion: To create a chat room using a Java Applet, you must install JVM on your machine. ActiveX control has some security problems. With AJAX just introduced, you can easily create a chat room program based on HTTP that can run without installing any software and is easy to maintain.

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: 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.