Click here to Skip to main content
12,399,975 members (46,796 online)
Click here to Skip to main content
Add your own
alternative version


236 bookmarked

Simple Chat Application in ASP.NET

, 20 Sep 2004
Rate this:
Please Sign up or sign in to vote.
Implementing a simple chat application using ASP.NET and remote scripting.


I ran into the problem of creating a chat room where two users can chat directly. I didn't like the idea of using server side code and doing all these post back which is not user friendly. I found that with the use of remote scripting, we can make a simple and fast chat application.


I built this application using the Remote Scripting client and server side implementation provided by Alvaro Mendez: Remote Scripting. I also used some chat room logic from Julien Couvreur.

Code Walkthrough

I'll start by examining the ChatEngine.cs file which contains all the logic. You'll find four classes in this file:

  1. The ChatUser that contains the user info (ID, name, active or not, last seen time, last message received):
    public class ChatUser : IDisposable    
      public string UserID;
      public string UserName;
      public bool IsActive;
      public DateTime LastSeen;
      public int LastMessageReceived;
      public ChatUser(string id,string userName)
        this.LastSeen=DateTime.MinValue ;
      public void Dispose()
        this.LastSeen=DateTime.MinValue ;
  2. The Message class contains information about the message (the message text, message type, sender ID):
    public class Message 
      public string user;
      public string msg;
      public MsgType type;
      public Message(string _user, string _msg, MsgType _type) 
        user = _user;
        msg = _msg;
        type = _type;
      public override string ToString()
          case MsgType.Msg:
            return this.user+" says: "+this.msg;
          case MsgType.Join :
            return this.user + " has joined the room";
          case MsgType.Left :
            return this.user + " has left the room";
        return "";
      public Message(string _user, MsgType _type) : this(_user, "", _type) { }
      public Message(MsgType _type) : this("", "", _type) { }
    public enum MsgType { Msg, Start, Join, Left }
  3. The ChatRoom class:

    Each chat room can have two users only represented by the two members FirstUser and SecondUser. The messages are stored in the ArrayList messages of Message instances. The class contains the common operations for a chat room like joining, sending message and leaving the room.

  4. The ChatEngine class: contains a HashTable of chat rooms.

Other operations in the class include creating new rooms and deleting the empty chat rooms.

Building The Application

I will build a simple app to demonstrate the usage of the Chat Engine classes. First, we create a simple page (default.aspx) where the user can enter his nickname (which is saved in the session). After that, the user enters the nickname of the other user he wants to chat with. The two user names are used to create the ID of the chat room. Then the user is redirected to chat.aspx with the name of the other passed in the query string and saved in a hidden variable.

In Chat.aspx, a chat room is created for the two users:

private void Page_Load(object sender, System.EventArgs e)
  if (AMS.Web.RemoteScripting.InvokeMethod(this))
       //if this is a callback function return

  txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
  if (!IsPostBack)
    if (Request.QueryString["userid"]!=null 
            && Request.QueryString["userid"]!="")
      ChatRoom room=ChatEngine.GetRoom(Session["UserName"].ToString() ,
      string s=room.JoinRoom(Session["UserName"].ToString(),
          Session["UserName"].ToString() );
      string strScript="< script >startTimer();< /script >";
      Response.Write("User id Missing");

On the client side, remote scripting is used to send messages to the chat room. Using Alvaro Mendez's implementation, calling server functions from the client is very simple. For example, when the user clicks the Enter key in the text box, a message is sent to the chat room using the following script:

function clickButton(e, buttonid)
  var bt = document.getElementById(buttonid); 
  if (typeof bt == 'object')
      if (e.keyCode == 13)
        return false; 
  if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
      if (event.keyCode == 13)
        return false; 
function button_clicked()
  RS.Execute("Chat.aspx", "SendMessage",document.Form1.txtMsg.value,
document.Form1.otherUser.value, callback, errorCallback);
function callback(result)
function errorCallback(result)
  alert("An error occurred while invoking the remote method: " 
  + result);

The RS object is defined in the rs.js file, so you have to include it in the aspx page. The Execute method takes the name of the page (chat.aspx) in the first parameter, and the name of the function in the second parameter. This function must be a public function in the page class you pass as the parameter of the server function to the Execute function. The last two parameters are for the callback and error callback functions. The result of the server function is passed as an argument to the callback function.

public string SendMessage(string msg,string toUserID)
    ChatRoom room=ChatEngine.GetRoom(Session["UserName"].ToString() ,toUserID);
    string res="";
    if (room!=null)
      res=room.SendMessage(msg,Session["UserName"].ToString() ,toUserID);
    return res;
  catch(Exception ex)
  return "";

As you can see, SendMessage takes the message as a parameter and the ID of the other user, adds this message to the chat room, and returns all the messages that have been sent that the user didn't receive yet.

The user can leave the room by clicking the Exit button.

private void btnExit_Click(object sender, System.EventArgs e)
    ChatRoom room=ChatEngine.GetRoom(Session["UserName"].ToString(), 
    room.LeaveRoom(Session["UserName"].ToString() );
  catch(Exception ex)

I also added a client side function that handles the onunload event of the form.

function Leave()
  RS.Execute("Chat.aspx", "LeaveRoom",document.Form1.otherUser.value);
public string LeaveRoom(string otherUser)
    ChatRoom room=ChatEngine.GetRoom(Session["UserName"].ToString() ,otherUser);
    if (room!=null)
            room.LeaveRoom(Session["UserName"].ToString() );
  catch(Exception ex)
  return "";

Remaining is to periodically update the client to receive the messages sent from the other user. A simple solution is to add a timer that makes a remote call to the server function.

var interval = "";
var i = 5;

function startTimer()
  interval = window.setInterval("tTimer()",1000);
function stopTimer()
  window.clearInterval (interval);
function tTimer()
  RS.Execute("Chat.aspx", "UpdateUser",document.Form1.otherUser.value, 
         callback, errorCallback);  
public string UpdateUser(string otherUserID)
    ChatRoom room=ChatEngine.GetRoom(Session["UserName"].ToString() ,
    if (room!=null)
      string res="";
      if (room!=null)
      return res;
  catch(Exception ex)
  return "";

A timer is added on the server to periodically clean and remove the empty chat rooms.

Timer ChatRoomsCleanerTimer=new System.Threading.Timer(
   new TimerCallback(ChatEngine.CleanChatRooms),null,3600000,3600000);
public static void CleanChatRooms(object state)
  foreach(object key in Rooms.Keys)
    ChatRoom room=(ChatRoom)Rooms[key.ToString()];
    if (room.IsEmpty())


Points of Interest

You can easily extend the ChatRoom class to allow multiple users per chat room.


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

Web Developer
Egypt Egypt
No Biography provided

You may also be interested in...

Comments and Discussions

Answerpublic chat Pin
Decepticons15-Nov-09 23:35
memberDecepticons15-Nov-09 23:35 
GeneralAdding Sound For IM & Users Entering the room Pin
James Forsythe13-Jan-09 6:07
memberJames Forsythe13-Jan-09 6:07 
Generalhow to implement this code... Pin
mayur_818922-Apr-10 8:57
membermayur_818922-Apr-10 8:57 version Pin
CurtSWRT1-Dec-08 0:54
memberCurtSWRT1-Dec-08 0:54 
GeneralRe: version Pin
biddydee17-Feb-09 4:46
memberbiddydee17-Feb-09 4:46 
GeneralAbout livechat script Pin
yogita kanire27-Nov-08 19:46
memberyogita kanire27-Nov-08 19:46 
GeneralGmail chat Pin
Aravind198328-Aug-08 5:10
memberAravind198328-Aug-08 5:10 
GeneralHi Pin
v-bhpati30-Jun-08 12:58
memberv-bhpati30-Jun-08 12:58 
GeneralAdd emotions(smileys) Pin
cooolremo10-Jun-08 0:26
membercooolremo10-Jun-08 0:26 
Questionpop up of private chat when msg sent? Pin
cooolremo6-Jun-08 2:36
membercooolremo6-Jun-08 2:36 
GeneralGreat Job Pin
Shyana26-May-08 3:26
memberShyana26-May-08 3:26 
Questionhow to run this application Pin
Gayathri_Sridaran18-May-08 22:24
memberGayathri_Sridaran18-May-08 22:24 
GeneralGmail chat / Yahoo messanger Pin
sharewithme2624-Feb-08 20:26
membersharewithme2624-Feb-08 20:26 
GeneralIssue I found Pin
Member 175104814-Jan-08 0:15
memberMember 175104814-Jan-08 0:15 
Thank u for code u have uploaded.
But I am getting one issue.
Using same logic I build a chat APplication.
Two user can chat in my application.
One user type someting it appear on others window(Textarea).
On every one sec I refresh the page to recieve the data and refresh the textArea.
The Isuue I got its working fine for some time after around 120 character. Textarea value is not changing what it receive from other user.
Can you tell the reason why its not displaying?
Questioni'm unable to run it Pin
way2roni23-Oct-07 22:00
memberway2roni23-Oct-07 22:00 
QuestionIs there any chat which does not refresh? Pin
s a n t o s h21-Aug-07 3:13
members a n t o s h21-Aug-07 3:13 
Generalone to one chatroom with ajax Pin
sridhar2117-Jul-07 5:14
membersridhar2117-Jul-07 5:14 
GeneralRe: one to one chatroom with ajax Pin
Mosalem17-Jul-07 5:16
memberMosalem17-Jul-07 5:16 
GeneralRe: one to one chatroom with ajax Pin
xlsprogrammer9-Jul-10 20:48
memberxlsprogrammer9-Jul-10 20:48 
Generalgood one Pin
santhoshg2oo411-Jul-07 4:28
membersanthoshg2oo411-Jul-07 4:28 
Questionhow to clear the single page in common chat application codes in Pin
karthikeyan_caleb5-Jul-07 20:38
memberkarthikeyan_caleb5-Jul-07 20:38 
Generalhi Pin
manikandanpro25-Jun-07 3:39
membermanikandanpro25-Jun-07 3:39 
GeneralRe: hi Pin
cooolremo29-Jun-08 17:22
membercooolremo29-Jun-08 17:22 
Questionhow can i create private rooms Pin
manikandanpro15-Jun-07 2:37
membermanikandanpro15-Jun-07 2:37 
QuestionGetting "system.threading.threadabortexception" Pin
honeysip31-May-07 2:29
memberhoneysip31-May-07 2:29 
Questionhow to run this project? Pin
siva chimmani31-May-07 0:01
membersiva chimmani31-May-07 0:01 
GeneralHide reload Pin
ihtezazshah15-Feb-07 1:02
memberihtezazshah15-Feb-07 1:02 
Questionwho calls RemoteScriptingCall.setResult function Pin
mamy7719-Sep-06 6:27
membermamy7719-Sep-06 6:27 
GeneralThe refresh method for the messages is not working Pin
aguilar.jesus4-Sep-06 9:50
memberaguilar.jesus4-Sep-06 9:50 
QuestionHow to distinguish messages? Pin
Rferj19-Aug-06 12:03
memberRferj19-Aug-06 12:03 
GeneralMutiple Users Chat Room Pin
Mosalem10-Aug-06 1:25
memberMosalem10-Aug-06 1:25 
QuestionRe: Mutiple Users Chat Room Pin
Bodog15-Aug-06 19:52
memberBodog15-Aug-06 19:52 
GeneralRe: Mutiple Users Chat Room Pin
Mosalem15-Aug-06 22:43
memberMosalem15-Aug-06 22:43 
QuestionHow to extend the chat room from two user's to multiple user's Pin
Praveen_Valla9-Aug-06 9:08
memberPraveen_Valla9-Aug-06 9:08 
AnswerRe: How to extend the chat room from two user's to multiple user's Pin
Mosalem10-Aug-06 1:22
memberMosalem10-Aug-06 1:22 
GeneralRe: How to extend the chat room from two user's to multiple user's Pin
lsharma14-Jul-07 10:21
memberlsharma14-Jul-07 10:21 
GeneralNice One!! Pin
VasTI123-Jul-06 23:25
memberVasTI123-Jul-06 23:25 
QuestionNeed popup facility to notify other user Pin
dharnendra shah20-Jul-06 23:49
memberdharnendra shah20-Jul-06 23:49 
QuestionHow to extend this to allow more than two users to chat in a same room Pin
Ramesh Duppati11-Jul-06 21:44
memberRamesh Duppati11-Jul-06 21:44 
AnswerRe: How to extend this to allow more than two users to chat in a same room Pin
Mosalem10-Aug-06 1:23
memberMosalem10-Aug-06 1:23 
Generalweb pages without timer Pin
ofsarac11-Jul-06 4:37
memberofsarac11-Jul-06 4:37 
GeneralTime Picker in ASp.Net Pin
PrasadHN6-Jul-06 23:33
memberPrasadHN6-Jul-06 23:33 
GeneralConfiguration Error Pin
longlh3-Jul-06 21:41
memberlonglh3-Jul-06 21:41 
Generalhelp plz its very urgent Pin
pankajmittal323-Jun-06 21:01
memberpankajmittal323-Jun-06 21:01 
GeneralRe: help plz its very urgent Pin
Mosalem10-Aug-06 1:23
memberMosalem10-Aug-06 1:23 
Generalgood Pin
ykg4-May-06 1:02
memberykg4-May-06 1:02 
Generali used this source Pin
lakshmi patil12-Dec-05 0:19
memberlakshmi patil12-Dec-05 0:19 
GeneralProblem in run the web page Pin
Ramalingma14-Sep-05 22:17
memberRamalingma14-Sep-05 22:17 
Generalv Pin
Anonymous16-Aug-05 1:56
sussAnonymous16-Aug-05 1:56 
Questionhow can show Chinese correctly? Pin
wangjue9029-Jul-05 21:51
memberwangjue9029-Jul-05 21:51 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 20 Sep 2004
Article Copyright 2004 by Mosalem
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid