Introduced
My first simple chat room was written in ASP 3.0. There are two textbox, they send a message to the program variable and then appear on a page refreshed every second. In those days, a real chat room had to use Java applets or ActiveX control. But it all changed after the advent of Ajax. Ajax is an asynchronous communication mechanism that combines XML and JavaScript. Now we can just use server code and a little JavaScript. This article is about how to use AJAX technology to build a simple chat room.
Sample Programs
The sample program is a single multi-user chat room. It maintains a list of logged-in users internally. The list will eliminate users who have expired session. It also supports commands such as/admin clear purge chat room/nick [name] To change the user's name.
You also need to know
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 StringCollection:
Hashtable users; StringCollection chat;
A Chatengine global instance is placed in the Global.asax.cs:
public static UChat.ChatEngine.IChatEngine Engine =new UChat.ChatEngine.ChatEngine ();
A JavaScript function is used asynchronously to display data from a global variable on the page:
function Settimers () {Timeid = Window.settimeout ("UpdateAll ()", refreshrate);}
Use each user-supplied name and ID to identify the user:
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 ) ));}}