Click here to Skip to main content
11,495,758 members (67,151 online)
Click here to Skip to main content

Building an AJAX based chat room in ASP.NET

, 1 Nov 2006 417.1K 19.8K 253
Rate this:
Please Sign up or sign in to vote.
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.

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

Share

About the Author

Dahan Abdo
Web Developer
United States United States
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).

Comments and Discussions

 
Questionit's very useful and amazing ! but... Pin
Member 106814069-Jun-14 11:28
memberMember 106814069-Jun-14 11:28 
QuestionSecurity Pin
lostandconfused123411-Dec-13 10:15
memberlostandconfused123411-Dec-13 10:15 
Questionneed a logout button Pin
AZAD CHOUHAN24-May-13 3:45
professionalAZAD CHOUHAN24-May-13 3:45 
GeneralMy vote of 5 Pin
kvreddy14-Feb-13 10:44
memberkvreddy14-Feb-13 10:44 
QuestionI want to add private chat please Pin
Member 305320118-Aug-12 5:11
memberMember 305320118-Aug-12 5:11 
QuestionPermission to use the software Pin
Lee Zhong Zheng24-Jul-12 21:45
memberLee Zhong Zheng24-Jul-12 21:45 
QuestionTrust level required for UChat Pin
Member 455521628-Jun-12 2:14
memberMember 455521628-Jun-12 2:14 
QuestionSmiley's Pin
anholm14-Jun-12 11:38
memberanholm14-Jun-12 11:38 
GeneralPermission to use code Pin
jessanthony21-Feb-12 5:49
memberjessanthony21-Feb-12 5:49 
QuestionLogout button code solution...links are not working :( no private chat is there :( Pin
Liju T Babu9-Feb-12 20:50
memberLiju T Babu9-Feb-12 20:50 
AnswerRe: Logout button code solution...links are not working :( no private chat is there :( Pin
VICK10-Dec-13 1:52
member VICK10-Dec-13 1:52 
Questionold chat history not removed Pin
chandan111110-Jan-12 0:03
memberchandan111110-Jan-12 0:03 
General.NET based voice conference room Pin
Gira Palmer3-Jun-11 4:38
memberGira Palmer3-Jun-11 4:38 
GeneralMy vote of 5 + a few improvements [modified] Pin
bradut29-Mar-11 13:14
memberbradut29-Mar-11 13:14 
First of all I congratulate the author for this piece of software: Despite it was published almost 6 years ago, to me UChat is still a great solution and one of the few free I was able to find.

While studying UChat, I had a couple of issues and solved some of them Smile | :)

1. converting to .Net 3.5
Instead of using Global.asax, I created a regular class [ChatCommon.cs] which only holds the static variable 'Engine':
public static IChatEngine Engine = new ChatEngine();
2. working with masterpages: To prevent 'garbage' being added by Response.write(), I had to add a Response.End(); in processGetMsg() and processUserList():
     protected void processGetMsg()
        {
            Response.Write(ChatCommon.Engine.BufferText);
            Response.End();
        }
3. implementing a logout button: this needed a little bit of work since the [Enter>]key was intercepted in order to send the message to the chat server
3.1. Added a "send" button beside "mytext" with:
OnClientClick="postText()"
3.2. Surrounded the "mytext" and the "send" button with a div
3.3. Declared the "send" button as the default button of the div, in order to intercept the [Enter] key
3.4. Removed the original javascript which did the same functionality. b/c it conflicted with some browsers

3.5. Created the logout() function in AjaxFunctions.js:
function logout() {
    rnd++;
    var chatbox = getElement("mytext");
    var chat = chatbox.value;
    chatbox.value = "..."; //"Logging out chat...";

    var userid = location.search.substring(1, location.search.length);
    var url = 'ChatServer.aspx?action=Logout&u=' + userid + '&t=' + encodeURIComponent(chat) + '&session=' + rnd;
    //alert('userid: ' + userid);
    req = getAjax();
 
    req.onreadystatechange = function() {
 
        if (req.readyState == 4 && req.status == 200) {
            updateAll();
        }
 
    }
 
    req.open('GET', url, true);
    req.send(null);
}

3.6. Added a Logout button which calls logout() in AjaxFunctions.js

3.7 Added processLogout() in [Chat]Server.aspx which calls Engine.remove() [You may find a nice implementation of logout explained in one of the comments bellow]

UNSOLVED ISSUES:
- I was not able to get UChat work properly in Chrome and Safari since it could not post messages and could not logout users, although I could see other users' activity.

[However, it works fine in IE, Opera and Mozilla]

I hope my update will help those who consider using UChat.

Bradut

modified on Tuesday, March 29, 2011 6:27 PM

GeneralRe: My vote of 5 + a few improvements [modified] Pin
thatraja27-Dec-11 18:33
mvpthatraja27-Dec-11 18:33 
GeneralRe: My vote of 5 + a few improvements [modified] Pin
bradut27-Dec-11 19:37
memberbradut27-Dec-11 19:37 
GeneralMy vote of 4 Pin
pgsaran887820-Jul-10 1:11
memberpgsaran887820-Jul-10 1:11 
Generalexecution problem Pin
jeremyblue13-Jul-10 7:29
memberjeremyblue13-Jul-10 7:29 
GeneralLeaving the chat Pin
quitstalin27-May-10 10:51
memberquitstalin27-May-10 10:51 
QuestionHow to convert this App. in Multiple Chat Rooms Pin
hiteshmca0717-Apr-10 2:07
memberhiteshmca0717-Apr-10 2:07 
GeneralMultiple Chat Rooms Pin
adiput24-Feb-10 21:26
memberadiput24-Feb-10 21:26 
QuestionHow to get to work in master pages ?. Pin
Member 359855130-Aug-09 3:28
memberMember 359855130-Aug-09 3:28 
GeneralNobody In Code Project Implemented one to one chat using asp.net Pin
ajay_zenta14-Aug-09 7:43
memberajay_zenta14-Aug-09 7:43 
GeneralRe: Nobody In Code Project Implemented one to one chat using asp.net Pin
arun$aini24-Mar-10 23:07
memberarun$aini24-Mar-10 23:07 
GeneralRe: Nobody In Code Project Implemented one to one chat using asp.net Pin
priyanka49910-Nov-10 19:56
memberpriyanka49910-Nov-10 19:56 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 1 Nov 2006
Article Copyright 2006 by Dahan Abdo
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid