Introduction:
My first simple Chat room was written in ASP 3.0. It's nothing more than two TextBoxes, they send messages to program variables and then display them on a page that refreshes every second. In that era, a real chat room had to use Java Applet or ActiveX control. But all this changed after the arrival of AJAX. AJAX is an asynchronous communication mechanism that combines XML and JavaScript. Now we can do it with just server code and a little JavaScript. This article introduces how to use AJAX technology to build a simple chat room.
Sample Program
The sample program is a single multi-user chat room. It maintains a list of logged in users internally. The list will remove users with expired sessions. At the same time, it also supports some commands such as /admin Clear to clear the chat room /nick [Name] to change the user name.
You also need to know that
this program uses a class called ChatEngine. This class controls all users and messages. Users are stored in a Hashtable, and messages are stored in a StringCollection:
Hashtable users;StringCollection chat;
A global instance of ChatEngine is placed in Global.asax.cs:
public static UChat.ChatEngine.IChatEngine Engine =new UChat.ChatEngine.ChatEngine();
A JavaScript function is used to asynchronously display the data in the global variable on the page:
function setTimers(){timeID = window.setTimeout( "updateAll()", refreshRate );}
Use the name and ID provided by each user to identify users:
public void AddUser(string id, string user){//make sure user name does not exist alreadyif(!UserExists(user)){//add user to users listusers. Add( id, user );//display a notification message to all users chat.Add( this.MakeServerMessage(string.Format(joinedfmt, user ) ));}}
Screenshots and implementation steps
The homepage shows the basic information of the chat room, such as how many people are in the chat room and the size of the ChatLog.
In order to be able to log into the chat room, a name must be provided.
When the Login button is clicked. The following code will be executed:
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."return;}Response.Redirect( "Server.aspx?action=Login&u=" + user );}
After some validation, the user is redirected to another page that uses the AddUser function to add the user to the user list. When this is all done. The user will be redirected to the Chat.aspx page, and the following JavaScript function will be executed on this page:
<script type="text/javascript">sniffBrowserType();//Shows loading.. screenshowLoadScreen();//Set the javascript timer and //loads user list and messages setTimers();setFocus('mytext');< /script><input type="text" class="mytext"id="mytext" onkeydown="captureReturn(event)">
When the user enters text and presses Enter. The following code will be executed:
// Capture the enter key on the input box and post messagefunction captureReturn( event ){if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)){postText();return false;}else {return true;}}}function postText(){rnd++;//Clear text box firstchatbox = getElement( "mytext" );chat = chatbox .value;chatbox.value = ""//get user GUID from urluserid = location.search.substring( 1, location.search.length );//construct Ajax Server URLurl = 'Server.aspx?action=PostMsg&u=' + userid + '&t=' +encodeURIComponent(chat) + '&session=' + rnd;//Create and set the instance //of appropriate XMLHTTP Request objectreq = getAjax();//Update page with new messagereq.onreadystatechange = function( ){if( req.readyState == 4 && req.status == 200 ) {updateAll();}}req.open( 'GET', url, true );req.send( null );}
Done! That's all. Nothing special, download the sample program and understand the code!
Original authorDahan Abdo
Translated yueue
original article address
download sample program:
codeproject
local download