This article assumes that you are familiar with ASP, XML and HTML.
Using this chat system, we can chat how we conventionally chat, in
public as well as private modes. Even though I've implemented most of the
conventional features such as unique nick names, the reader is welcome
to incorporate any other features they require. Please note that I
didn't worry much about memory usage on the server side and the code that
allots user ids obviously needs improvement.
Let us talk about the overall functionality. The message from the browser is
sent to the server via Microsoft's XMLHTTP Object. Using this same XMLHTTP
Object, the messages are retrieved from the server and displayed on the
page. The users list comes from the server along with messages. It is
currently configured so that the browser requests the current users list from the
server every 5 seconds.
How it works
The following screens are identical to the chat system.
C H A T
Your Nick Name:
User: Najeeb
Logout
Public
Private
Once a user logs into the chat system, that user is given a unique userid,
an integer stored in the chat page, and their user name is stored in the
ASP Application object.
A message from any browser is stored in the server in such a way that if
the mode of the message is private then the message is stored in the
application object against each user in the private user list which comes
along the message and if public mode then message is stored for each user
available in the application object.
In the user page messages, as well as the user list, get updated in two ways.
First, if a user sends any message to the server by clicking the 'Send'
button, then any messages in this user's account and the current user list
(available in the server side application object) are sent to the browser.
Second, the timer event set in the page to run every 5 seconds accomplishes
the same thing.
The following files are used in the chat system.
Login.asp :
<%
Response.Expires = 0
'if this page is requested by clicking the Submit button
if request("submit") <> "" then
dim count,user,strMsg
user = Request.form("txtUser")
'check for white space
if instr(user," ") > 0 then
strMsg = "space is not allowed, please"
end if
'get the total no. of online users
count = cint(Application("usercount"))
'check for duplicate name
for i = 1 to count
if trim(user) = application("name" & i) then
strMsg = "Please enter another Nick name"
end if
next
'if everything is OK,
'then store the user name in the application object as well as
'the session object, increment the user count by one, and
'open the chat window
if strMsg = "" then
count = count + 1
Application("usercount") = count
Application("name" & count) = user
session("user") = user
Response.Write "<script>" & _
window.open(""chat.html?userid=count & "Name*" & user & _
""","""",""toolbar=no,location=no,directories=no," & _
"status=no,menubar=no,resizable=no,scrollbars=no," & _
"copyhistory=no,width=650,height=300"")</script>"
Response.End
end if
end if
%>
<html>
<title>C H A T </title>
<script>
//to maintain a standard in names,
//name entered by the user is changed to lowercase
//except the first character which is to uppercase.
function changeCase(){
var strName;
var data = document.frm.txtUser.value;
strName = data.substr(0,1).toUpperCase();
strName += data.substr(1).toLowerCase();
document.frm.txtUser.value = strName;
}
</script>
<body onload="document.frm.txtUser.focus();">
<form name=frm action="login.asp" method="post" onsubmit="changeCase()">
<table border=1 width=50% bgcolor=DarkSeaGreen align=center>
<tr><td align=center>
<font color=darkblue size=7>C H A T</font><br>
<font color=red><%= strMsg %></font>
<br>
Your Nick Name:
<input size=15 name=txtUser>
<input type=submit value="Submit" name=submit>
</td></tr></table>
</form>
</body>
</html>
Chat.asp :
<%
Response.Expires = 0
dim
strXML,msgXML,usersXML,userList,user,apname,msg,count
'strXML - a string to store the entire xml document
' which is sent to the browser.
'msgXML - a string to store the message content.
' It is a part of the strXML.
'usersXML - a string to store the users content.
' It is a part of the strXML.
'userList - a string array to store the users' names
' coming from the client (browser) to whom
' the message from the client should be sent.
'user - name of the user stored in the session object.
'apname - the user name stored in the application object.
'msg - the message coming from the client.
'count - used as counting index
'populate the user array for private message
userList = split(request("userList"),"-")
user = session("user")
msg = request("Msg")
Application.Lock
'add msg to the Message Queue
if trim(msg) <> "" then
if request("userList") <> "" then 'private msg
for i = 0 to ubound(userList)
count = cint(application(userList(i) & "_count")) + 1
application(userList(i) & "_msg_from_" & count) = user
application(userList(i) & "_msg_" & count) = msg
application(userList(i) & "_count") = count
next
else 'public msg to all
for i = 1 to cint(application("usercount"))
apname = application("name" & i)
if application( apname & "_count") <> ""
then
count = cint(application( apname & "_count"))
else
count = 0
end if
if apname <> "" AND trim(apname) <>
trim(user) then
count = count + 1
application(apname & "_msg_from_" & count) = user
application(apname & "_msg_" & count) = msg
application(apname & "_count") = count
end if
next
end if
end if
'get messages to this user,
'store them in msgXML, and
'after storing the messages delete them
'from the application object.
if application(user & "_count") <> "" then
for i = 1 to cint(application(user & "_count"))
msgXML = msgXML & "<msg><from>" & _
"application(user & "_msg_from_" & i) & _
"</from><dat>" & _
application(user & "_msg_" & i) & _
"</dat></msg>"
application(user & "_msg_from_" & i) = ""
application(user & "_msg_" & i) = ""
next
application(user & "_count") = 0
end if
'get all the online user names
'in the application object, and store them in usersXML
if application("usercount") <> "" then
usersXML = "<users>"
for i = 1 to cint(Application("usercount"))
if Application("name" & i) <> "" then
usersXML = usersXML & "<name>" & _
Application("name" & i) & "</name>"
end if
next
usersXML = usersXML & "</users>"
end if
'make the full XML content as follow.
strXML = "<chat>" & usersXML & msgXML & "</chat>"
'send the XML content to the client.
response.write(strXML)
Application.UnLock
%>
Chat.html :
<html>
<head>
<title>C H A T</title>
<script>
//hLoc - to parse the username and the userid
var hLoc = document.location.href;
//to manage the xml document
var objDOM = new
ActiveXObject("Microsoft.XMLDOM");
//to establish a http connection between the
server
//and the client, thereby sending and
receiving
//message to and from the server
//without submitting the page
var xmlh = new
ActiveXObject("Microsoft.XMLHTTP");
//to store the user name
var userName = '';
//to identify whether the server is contacted
//by clicking the send button OR
//the routine timer event
var isBtnPressed = false;
//to display the incoming messages
function listMsg() {
var nodes,strTxt;
objDOM.loadXML(Chatdata.documentElement.xml);
nodes = objDOM.getElementsByTagName("msg");
strTxt = '';
if (document.frm.MsgScreen.innerText != '')
strTxt = document.frm.MsgScreen.innerText;
for(i=0;i<nodes.length;i++){
strTxt += '\n' + nodes.item(i).firstChild.text +
' >>' + nodes.item(i).lastChild.text ;
}
document.frm.MsgScreen.innerText = strTxt;
}
//to display the incoming user list
function listUser() {
var nodes,strHtml;
var selList = new
Array();
var newList = new
Array();
objDOM.loadXML(Chatdata.documentElement.xml);
nodes = objDOM.getElementsByTagName("name");
//getting the selected users
for(i=0,j=0;i<document.frm.usrList.length;i++){
if(document.frm.usrList.options[i].selected==true)
selList[j++] = document.frm.usrList.options[i].text;
}
//getting the current user list
for(i=0;i<nodes.length;i++){
newList[i] = nodes.item(i).text;
}
newList.sort();
//updating the user list in the page
for(i=0;i<newList.length;i++){
document.frm.usrList.options[i] = new
Option(newList[i]);
}
//removing the excess users in the page if
any
for(i=newList.length;i<document.frm.usrList.length;i+
+)
document.frm.usrList.options[i] = null;
//selecting the users in this updated user
list
for(i=0;i<document.frm.usrList.length;i++) {
for(j=0;j<selList.length;j++) {
if(document.frm.usrList.options[i].text==selList[j])
document.frm.usrList.options[i].selected =true ;
}
}
}
//to configure the initial settings
function init() {
var index1,index2,index3;
index1 = hLoc.indexOf("=")+1;
index2 = hLoc.indexOf("Name");
index3 = hLoc.indexOf("*");
document.all("userid").value =
hLoc.substr(index1,index2-index1);
userName = hLoc.substr(index3+1)
user.innerHTML = "<b>User: <font color=RoyalBlue>" +
userName + "</font></b>";
sendMsg('joined the room');
id = setInterval("requestMsg()",5000);
}
//to do some housekeeping before and after sending
the msg
//to the server
function sendMsg(data) {
isBtnPressed = true;
if (data != '')
document.frm.msgData.value = data;
requestMsg();
if (document.frm.msgData.value != ''){
document.frm.MsgScreen.innerText =
document.frm.MsgScreen.innerText +
'\n' + userName + ' >>' +
document.frm.msgData.value ;
document.frm.msgData.value = '';
}
isBtnPressed = false;
}
//to send the msg entered to the server
function requestMsg() {
var data,userList;
//get the selected users if message type is
private
userList = '';
if (document.frm.msgType[1].checked == true){
for(i=0;iif(document.frm.usrList.options[i].selected)
userList +=
document.frm.usrList.options[i].text + '-';
}
if (isBtnPressed == true)
data = document.all("msgData").value;
else
data = '';
xmlh.open("POST","chat.asp?Msg=" + data + "&UserList;=" +
userList,false);
xmlh.send("");
objDOM.loadXML(xmlh.ResponseText);
Chatdata.documentElement = objDOM.documentElement;
listUser();
listMsg();
}
function logout(){
sendMsg('left the room.');
document.frm.submit();
}
</script>
</head>
<xml id="Chatdata"><chat></chat></xml>
<body onload="init()"
bgcolor=DarkSeaGreen>
<form name=frm method=post action="logout.asp"
onsubmit="return false;">
<input type=hidden
name=userid value=''>
<table border=0 align=center width=60%>
<tr><td><div
id="user"></div></td>
<td
align=right><A href="javascript:logout();">Logout</a>
</td></tr>
<tr><td><textarea name=MsgScreen cols=50 rows=10 readonly>
Welcome to the CHAT System</textarea>
</td>
<td align=right><div id="list">
<select name=usrList multiple size=10 style="width:150">
</select></div>
</td>
</tr>
<tr><td>
<input name=msgData size=58 value=''>
<input type=button name=Submit value=Send
onclick="sendMsg('')">
</td>
<td align=center><input type=radio name=msgType
value="Pub" checked>
<font color=white><b>Public
<input type=radio name=msgType value="Pri">Private</b>
</font>
</td>
</tr>
</table>
</form>
</body>
</html>
Logout.asp :
<%
dim user
Response.Expires = 0
user = Application("name" & request("userid"))
Application("name" & request("userid")) = ""
session.abandon
if application(user & "_count") <> "" then
for i = 1 to cint(application( user & "_count"))
application(user & "_msg_from_" & i) = ""
application(user & "_msg_" & i) = ""
next
end if
application(user & "_count") = ""