Click here to Skip to main content
11,704,509 members (56,914 online)
Click here to Skip to main content

Simple Chat application using AJAX

, 28 Oct 2010 CPOL 52.2K 7.8K 54
Rate this:
Please Sign up or sign in to vote.
Simple Chat application using AJAX

Introduction

Here is a simple Chat application to demonstrate the use of XMLHttpRequest (AJAX) in ASP.NET. This is a one to one user chat application, but can be easily extended to support multi user chat also.

As for a demo application, no extra user details are maintained while user registration or no CAPTCHA check or other Security is used.

The main code which is responsible for the AJAX communications is the same as is explained in my previous article which can be found at AJAXDemo.aspx.

So the function AJAXRequest() is used for transferring all the data between the browser and the server.

Background

For all the details regarding the AJAXRequest() function, please refer to AJAXDemo.aspx.

In this chat application, some part of data (e.g. RequestCode, username, password) is sent through the HTTP headers, and some data like the message and userlist is sent normally in the content.

This easily explains the use of most of the AJAX data exchange possibilities.

Using the Code

The demo application is a ASP.NET web application. It uses Microsoft SQL database to store user messages and user logins.

The database .mdf is included in the APP_Data folder, and also the file "DatabaseScript.sql" contains all the database scripts to setup a new database.

Currently, I have commented out the code for maintaining the message history in Database stored procedure, but it can be enabled if one wants.

The communication between browser -> Server -> browser happens in the following way:

  1. Client(browser) sends the request along with the RequestCode.
  2. Request code is parsed at the server to determine what the request is for. (E.g.. Login, Logout, SendMessage, ReceiveMessage, etc.)
  3. Server Handles the request, processes it and sends the appropriate Response back, along with the requested data.
  4. Recipient client always polls the Server for Messages. Once Server has Message for Recipient, the message is sent in the response from server.
var MessagePollingInterval = 3000 ;  	// Interval of polling for message
var OLUsersPollingInterval = 9000;  		// Interval of polling for online users 

These are variables that hold the polling interval.

Messages are exchanged from and to server in an encrypted way. The encryption/decryption algorithm used in this application is the simple substitution cipher.

var EncryptionKey = 3;  //Encryption Key: 0 to disable encryption

This holds the encryption key which should be the same at the client and server end.

Following are the encryption/decryption functions:

function Encrypt(PlainText, Key) {
    var to_enc = PlainText.toString().replace(/^\n+/, "").replace
	(/\n+$/, "");  //Nozel: remove \n

	var xor_key=Key;
	var the_res="";//the result will be here
	for(i=0;i<to_enc.length;++i)
	{
	    ////the_res += String.fromCharCode((xor_key ^ to_enc.charCodeAt(i))); 
		//Nozel:  Xor Cipher . 
		//But encoded characters are not always allowed in http headers

	    if (to_enc.charCodeAt(i) <= 32) {
	        //Keep c as it is
	        the_res += String.fromCharCode((to_enc.charCodeAt(i))); //Nozel: Bypass 
			//Invalid characters which are not supported in Http headers
	     }
	    else {
	        the_res += String.fromCharCode
		((to_enc.charCodeAt(i)) - Key); //Nozel: Normal substitution Cipher
	    }
	}
	return(the_res);
}

function Decrypt(CipherText, Key) {
    var to_dec = CipherText;
    var xor_key = Key;
    var PlainText = "";
    for (i = 0; i < to_dec.length; i++) {

       ///// PlainText += String.fromCharCode((xor_key ^ to_dec.charCodeAt(i)));   
     //Nozel:  Xor Cipher . But encoded characters are not always allowed in HTTP headers

        if (to_dec.charCodeAt(i) <= 32) {
            //Keep c as it is
            PlainText += String.fromCharCode((to_dec.charCodeAt(i)));  
	  //Nozel:   Bypass Invalid characters which are not supported in HTTP headers
        }
        else {
            PlainText += String.fromCharCode
		((to_dec.charCodeAt(i)) + Key);  //Nozel:   Normal substitution Cipher
        }
    }
    return (PlainText);
} 

A similar function is implemented in the C# code in the server side handler to perform encryption/decryption.

Here is a code snippet of how the message is sent through an Ajax request:

function SendMessage() {
    if (ValidateSendMessageWindow()) {
        var URL = "SecureChatServer.ashx";
        var covert = "False";
        if (URL == null) { alert("Request URL is Empty"); }
        else {
            HTMLmessage = document.getElementById('Message').value.toString().replace
			(/\r\n?/g, '<br/>');
            message = Encrypt(HTMLmessage, EncryptionKey);
            recepient = Encrypt
		(document.getElementById('Recepient').value, EncryptionKey);
            AjaxRequest(ProcessSendMessageResponse, URL, "POST", 
		{Message:message , Recepient:recepient}, '', { RequestCode: 'SC005'});

			//.
			//.
			//.
			}}} 

All the required data is passed to the 'AjaxRequest' function which sends the data to generic handler 'SecureChatServer.ashx' .

Here is the code which is executed for the RequestCode: SC005:

 LoggedInUser = userlogin.IsUserLoggedIn(SessionID, UserIPAddress);
 if (LoggedInUser != null)  // Check is user is logged in
 {
  Messages newMessage = new Messages(); // Message Data Access Layer

 Message = Decrypt(context.Request.Params["Message"], 
	EncryptionKey);  // Extract the message data from the request and decrypt it.
 Recepient = Decrypt(context.Request.Params["Recepient"], 
	EncryptionKey);  // Extract the recipient data from the request and decrypt it.
 if (newMessage.WriteMessage(LoggedInUser, Recepient, 
	Message))  //Write the message to database through Message Data access layer
  {
 context.Response.AddHeader("CustomHeaderJSON", 
	"ResponseStatus:'RS-OK'");  //add the Success indicator to the response header
 }
 else
 {
 context.Response.AddHeader("CustomHeaderJSON", 
    "ResponseStatus:'RS-Failed'");  //add the Failure indicator to the response header
 }

.

.

.
} 

This response with the newly added success/failure indicators in HTTP header is sent back by the server.

And finally after the AJAX request is completed, the Handler function is executed. All the responses from the server are available in the handler function.

In this case, the handler function specified is 'ProcessSendMessageResponse', and here is its definition:

function ProcessSendMessageResponse() {
   var ResponseStatus = GetHeader(ResponseHeaderJSON, 'ResponseStatus');
   if (ResponseStatus == "RS-OK") {
       //.
       //.
       //.
       }}

As you see, the value of 'ResponseStatus' is extracted from the Response HTTP headers which are readily available in the function. As the 'ResponseHeaderJSON' is a JSon string, the function 'GetHeader' is used to extract a particular value in JSon string.

The value of the 'ResponseStatus' is then checked to notify Success/Failure in sending the message.

A similar process is used for all the functions such as Receive message, Login, Logout, Get Online Users list, etc.

Most of the UI features like Window dragging, tooltips, smooth show/hide, etc. are implemented using JQuery libraries.

Points of Interest

This is a basic implementation and can be extended to support other features like more detailed user Registration, multi user chat and other features of normal Chat application.

The main purpose of this application is to provide a simple and clear understanding of how XmlHttpRequest with ASP.NET can be used for different purposes in a Web Application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nozel Rosario : 4583847
Software Developer (Senior)
India India
function Nozel_Rosario(Imagination, Creativity, Computer_Programming) {
var Innovation = Imagination + Creativity * Computer_Programming ;
return Innovation;
}

You may also be interested in...

Comments and Discussions

 
Questionerror Pin
Member 1147560424-Feb-15 1:56
memberMember 1147560424-Feb-15 1:56 
QuestionIts awesome but.. Pin
agent_suwastica16-Aug-13 17:27
memberagent_suwastica16-Aug-13 17:27 
Questionproblem connecting database Pin
scorpionrose1-Feb-13 2:31
memberscorpionrose1-Feb-13 2:31 
i got an error, well, a cannot login or register, and i create a user in scritp code, but is the same, o got an error, like code04- code07

my problem is that my db is not SecureChat but OttensSecureChat.
if i make a new db it always start with Ottens and than the name i call it.
What i have to change so it will connect to my db
Questionprblems with db Pin
scorpionrose1-Feb-13 1:17
memberscorpionrose1-Feb-13 1:17 
QuestionHelp Pin
biomanimca27-Dec-12 1:18
memberbiomanimca27-Dec-12 1:18 
AnswerRe: Help Pin
Nozel Rosario : 458384727-Dec-12 22:35
memberNozel Rosario : 458384727-Dec-12 22:35 
Questionrequest cannot be processed,pls try again Pin
Member 442881011-Dec-12 3:51
memberMember 442881011-Dec-12 3:51 
AnswerRe: request cannot be processed,pls try again Pin
Nozel Rosario : 458384727-Dec-12 22:57
memberNozel Rosario : 458384727-Dec-12 22:57 
QuestionGreate Work Pin
AJMAL SHAHZAD7-Jul-12 20:04
memberAJMAL SHAHZAD7-Jul-12 20:04 
AnswerRe: Greate Work Pin
Nozel Rosario : 45838478-Jul-12 19:30
memberNozel Rosario : 45838478-Jul-12 19:30 
GeneralMy vote of 5 Pin
manoj kumar choubey3-Feb-12 19:26
membermanoj kumar choubey3-Feb-12 19:26 
GeneralRe: My vote of 5 Pin
Nozel Rosario : 45838478-Jul-12 19:30
memberNozel Rosario : 45838478-Jul-12 19:30 
Questionhelp Pin
daedusp8-Sep-11 11:14
memberdaedusp8-Sep-11 11:14 
AnswerRe: help Pin
daedusp8-Sep-11 11:31
memberdaedusp8-Sep-11 11:31 
AnswerRe: help Pin
Nozel Rosario : 45838478-Sep-11 22:31
memberNozel Rosario : 45838478-Sep-11 22:31 
GeneralRe: help Pin
daedusp10-Sep-11 17:36
memberdaedusp10-Sep-11 17:36 
GeneralRe: help Pin
Nozel Rosario : 458384711-Sep-11 19:08
memberNozel Rosario : 458384711-Sep-11 19:08 
GeneralCouldnt download the code Pin
Member 455875410-Feb-11 2:11
memberMember 455875410-Feb-11 2:11 
AnswerRe: Couldnt download the code Pin
Nozel Rosario : 458384710-Feb-11 5:06
memberNozel Rosario : 458384710-Feb-11 5:06 
GeneralRe: Couldnt download the code Pin
Member 455875410-Feb-11 21:30
memberMember 455875410-Feb-11 21:30 
AnswerRe: Couldnt download the code Pin
Nozel Rosario : 458384711-Feb-11 9:58
memberNozel Rosario : 458384711-Feb-11 9:58 
Generalcan't open .mdf file Pin
halcyondays8-Jan-11 20:36
memberhalcyondays8-Jan-11 20:36 
AnswerRe: can't open .mdf file Pin
Nozel Rosario : 45838478-Jan-11 23:28
memberNozel Rosario : 45838478-Jan-11 23:28 
Generalerror while sending msg Pin
Member 305559723-Nov-10 22:14
memberMember 305559723-Nov-10 22:14 
AnswerRe: error while sending msg Pin
Nozel Rosario : 458384724-Nov-10 19:39
memberNozel Rosario : 458384724-Nov-10 19:39 
QuestionQuestion Pin
urbancommando50816-Nov-10 10:33
memberurbancommando50816-Nov-10 10:33 
GeneralRe: Question Pin
Nozel Rosario : 458384716-Nov-10 20:33
memberNozel Rosario : 458384716-Nov-10 20:33 
GeneralMy vote of 5 Pin
saxenaabhi62-Nov-10 13:46
membersaxenaabhi62-Nov-10 13:46 
GeneralRe: My vote of 5 Pin
Nozel Rosario : 45838477-Nov-10 7:28
memberNozel Rosario : 45838477-Nov-10 7:28 
Generalmy vote5 Pin
ShashankSinghThakur28-Oct-10 8:32
memberShashankSinghThakur28-Oct-10 8:32 
GeneralRe: my vote5 Pin
Nozel Rosario : 458384728-Oct-10 19:04
memberNozel Rosario : 458384728-Oct-10 19:04 

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
Web02 | 2.8.150819.1 | Last Updated 28 Oct 2010
Article Copyright 2010 by Nozel Rosario : 4583847
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid