Click here to Skip to main content
15,174,296 members
Articles / Web Development / HTML
Article
Posted 1 Nov 2006

Stats

561K views
141.4K downloads
253 bookmarked

Building an AJAX based chat room in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.86/5 (85 votes)
1 Nov 20063 min read
Build an HTTP based chat room without the need for a Java Applet or an ActiveX control.

Introduction

I built my first chat room using ASP 3.0. It was nothing more than two text boxes that sent messages to an application variable that gets put on the page when it refreshes every second. At that time, building a true chartroom required using a Java Applet or an ActiveX control. HTTP based chart rooms suffered from the same issues my basic chat room suffered from. These issues included constant page refreshes which causes an annoying flicker and sound. That has changed with the introduction of AJAX. AJAX is the combination of Asynchronous calls with JavaScript and XML. A true chat room could now be built using server side code with some JavaScript. This article is not an introduction to AJAX. It is assumed that you have a basic knowledge of using AJAX with ASP.NET. This article is an introduction to using AJAX techniques to create a basic chat room.

The sample application

The sample application is a single chat room with many users. It maintains a list of users that gets populated as users log in. The list gets shorter as a user session times out. The chat room also permits the execution of some command-line-like functions such as /admin clear which clears the chat room, and /nick [Name] which changes the current user's nickname.

What you need to know

This application uses a class called ChatEngine. This class handles all chat room messages and users. Users are stored in a Hashtable, and messages are stored in a StringCollection.

C#
Hashtable users;
StringCollection chat;

A global instance of ChatEngine is declared in Global.asax.cs to be shared by all users of the chat room:

C#
public static UChat.ChatEngine.IChatEngine Engine = 
              new UChat.ChatEngine.ChatEngine();

A JavaScript timer function is used to asynchronously pull data from the global variable and renders it on the page.

JavaScript
function setTimers()
{
  timeID = window.setTimeout( "updateAll()", refreshRate );
}

Each user is identified by a supplied username and a GUID.

C#
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 ) ));
      }
}

Screenshots and application workflow

Sample screenshot

The default page shows the basic info of the current chat session, such as number of users and the size of the chat log. In order for a user to join the chat room, a user name must be supplied.

When the Login button is clicked, the following function is executed:

C#
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 directed to a page where he is added to the users' list using the AddUser function above. When this is done, the user is redirected to the chat.aspx page where the following JavaScript functions are executed:

Sample screenshot

JavaScript
<script type="text/javascript">
      sniffBrowserType();
      //Shows loading.. screen
      showLoadScreen();
      //Set the javascript timer and 
      //loads user list and messages 
      setTimers();
      setFocus('mytext');
</script>

When a user types some text and hits the Enter key, the following code gets executed:

HTML
<input type="text" class="mytext" 
       id="mytext" onkeydown="captureReturn(event)">
JavaScript
// 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()
{
      rnd++;
      //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 );
}

That is all there is to it. Nothing too fancy. Download the sample application and go through the code. The code has been commented properly.

Conclusion

Building a chat room using a Java Applet requires JVM to be installed on the user’s PC. Using an ActiveX control has security issues attached to it. With the introduction of AJAX, you could build an HTTP based chat-room that does not require the user to download or install software. It is also easy to create and maintain.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Dahan Abdo
Web Developer
United States United States
Dahan Abdo is a Software Project Manager. He is an early adapter of the .NET technology. He has been developing Web applications and services since .NET beta1. He enjoys programming in C# and developing web applications. He also enjoys working on large and complex projects using innovative design and cutting edge technologies.
He recently became a Microsoft Certified Applications Developer (MCAD).
Dahan Abdo is also a three time Microsoft Most Valuable Professional (MVP).

Comments and Discussions

 
GeneralExcellent Pin
nish8nish15-Dec-06 22:41
Membernish8nish15-Dec-06 22:41 
Questionvb.net version? Pin
a8le14-Dec-06 21:33
Membera8le14-Dec-06 21:33 
GeneralError Pin
Elavarasu11-Dec-06 23:20
MemberElavarasu11-Dec-06 23:20 
GeneralMultiple Rooms Pin
treend11-Dec-06 0:23
Membertreend11-Dec-06 0:23 
GeneralThanks Pin
paulbassguy9-Dec-06 16:36
Memberpaulbassguy9-Dec-06 16:36 
GeneralLogout button Pin
Britney S. Morales15-Nov-06 11:54
MemberBritney S. Morales15-Nov-06 11:54 
GeneralRe: Logout button Pin
Dahan Abdo16-Nov-06 18:01
MemberDahan Abdo16-Nov-06 18:01 
GeneralGreat Work! Pin
jmawebco15-Nov-06 8:28
Memberjmawebco15-Nov-06 8:28 
I just wanted to say thanks for the great work and a super nice application. A couple of suggestions I have would be to allow private rooms as well as the use of authentication to again access to the private rooms.

I look forward to the multi chat room version.

Jaime

Smile | :)
GeneralError to run over IIS Pin
Britney S. Morales9-Nov-06 12:09
MemberBritney S. Morales9-Nov-06 12:09 
GeneralRe: Error to run over IIS Pin
Dahan Abdo9-Nov-06 18:40
MemberDahan Abdo9-Nov-06 18:40 
GeneralRe: Error to run over IIS Pin
Britney S. Morales15-Nov-06 11:50
MemberBritney S. Morales15-Nov-06 11:50 
Generala bug [modified] Pin
ctf_yi7-Nov-06 16:27
Memberctf_yi7-Nov-06 16:27 
GeneralRe: a bug Pin
Dahan Abdo9-Nov-06 18:32
MemberDahan Abdo9-Nov-06 18:32 
Jokevery good Pin
Mauricio_Junior7-Nov-06 7:30
MemberMauricio_Junior7-Nov-06 7:30 
GeneralRe: very good Pin
Dahan Abdo9-Nov-06 18:25
MemberDahan Abdo9-Nov-06 18:25 
GeneralAJAX + PHP Chat Pin
stevehnsn7-Nov-06 7:29
Memberstevehnsn7-Nov-06 7:29 
GeneralRe: AJAX + PHP Chat Pin
Dahan Abdo9-Nov-06 18:41
MemberDahan Abdo9-Nov-06 18:41 
GeneralPrivate Messages Pin
sayedwasim6-Nov-06 22:03
Membersayedwasim6-Nov-06 22:03 
GeneralRe: Private Messages Pin
Dahan Abdo9-Nov-06 18:42
MemberDahan Abdo9-Nov-06 18:42 
QuestionRe: Private Messages Pin
dunglesi21-Nov-06 23:29
Memberdunglesi21-Nov-06 23:29 
Generalnice work Pin
Ahmed Galal6-Nov-06 11:31
MemberAhmed Galal6-Nov-06 11:31 
GeneralRe: nice work Pin
Zhengzhe Yu13-Nov-06 10:54
MemberZhengzhe Yu13-Nov-06 10:54 
GeneralJamal Pin
Chaudhryb6-Nov-06 9:37
MemberChaudhryb6-Nov-06 9:37 
GeneralRe: Jamal Pin
Dahan Abdo9-Nov-06 18:32
MemberDahan Abdo9-Nov-06 18:32 
QuestionSession QueryString Param? Pin
T.D. Ryan3-Nov-06 3:21
MemberT.D. Ryan3-Nov-06 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.