5,693,936 members and growing! (15,475 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » Samples     Intermediate

Building an AJAX based chat room in ASP.NET

By Dahan Abdo

Build an HTTP based chat room without the need for a Java Applet or an ActiveX control.
C#, Javascript, XML, HTML, Windows, .NET 1.1, .NET, Ajax, ASP.NET, Visual Studio, VS.NET2003, Dev

Posted: 1 Nov 2006
Updated: 1 Nov 2006
Views: 117,571
Bookmarked: 143 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
58 votes for this Article.
Popularity: 8.08 Rating: 4.58 out of 5
6 votes, 10.5%
1
0 votes, 0.0%
2
3 votes, 5.3%
3
7 votes, 12.3%
4
41 votes, 71.9%
5

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.

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:

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.

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

Each user is identified by a supplied 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 ) ));
      }
}

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:

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

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

<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()
{
      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

About the Author

Dahan Abdo


Dahan Abdo is a Software Project Manager with Human Resources Administration in NYC. 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).
Occupation: Web Developer
Location: United States United States

Other popular Ajax and Atlas articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 105 (Total in Forum: 105) (Refresh)FirstPrevNext
Generalsimple problem!!memberamar726:38 19 Nov '08  
GeneralHow to Implement One 2 One Chat in this Example ...........memberharryforum21:48 22 Oct '08  
QuestionCan't see the inputbox and buttonmemberdansu995314:55 11 Oct '08  
Generalhow to implement one to one chatmembershwethashiv8:21 27 Mar '08  
GeneralRe: how to implement one to one chatmemberharryforum21:46 22 Oct '08  
GeneralAnother approach...memberDoodie Woddy Doodlechips15:15 11 Feb '08  
GeneralHow to get GUID from usernamememberjumpstart792:17 23 Jan '08  
GeneralProblem with Chat bumping everyone and clearing chatmemberMember 16681914:22 16 Jan '08  
Generalweb messenger using asp 2.0 with databasememberjemille22:17 7 Jan '08  
QuestionClear old textmemberadslourenco2:28 26 Nov '07  
QuestionPrivate Chat HELP!!!!!memberarindam.roy1:21 27 Oct '07  
GeneralNew VersionmemberCylindrixCode3:03 14 Oct '07  
GeneralExcellent Articlemembermano varghese2:53 12 Oct '07  
GeneralNew Versionmembermfc_surfer2:54 4 Sep '07  
QuestionHow to use this application as online help chat?membersarajames1:09 26 Aug '07  
Questioncan't use html in messagemembermansourweb3:02 12 Aug '07  
AnswerRe: can't use html in messagemembertempsh18:35 13 Aug '07  
AnswerRe: can't use html in messagememberapr ~ asp19:13 8 Aug '08  
QuestionRegarding User sesseiontimed outmemberTheFrnd1:42 25 Jul '07  
Generalhow to room based ?memberpeacefire5:23 24 Jul '07  
GeneralRe: how to room based ?memberjimmy.jiang17:05 4 Mar '08  
GeneralProblem with Firefoxmembertempsh21:40 4 Jul '07  
GeneralRe: Problem with Firefoxmembercarlosaegithus7:23 2 Oct '07  
GeneralRe: Problem with Firefoxmembertempsh10:08 2 Oct '07  
GeneralRe: Problem with Firefoxmembersenthil_os22:13 3 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Nov 2006
Editor: Smitha Vijayan
Copyright 2006 by Dahan Abdo
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project