Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Chat Lag 2

Status
Not open for further replies.

m0nty005

IS-IT--Management
Apr 24, 2004
27
US
fellow geeksters,

I want to create a nice working chat application! I've created one using ASP/SQL Server w/ Sessions. The only thing I do not like about my application so far is I've included a Meta-tag to Refresh the browser every 15 seconds so messages can be updated.... And that's kinda ugly! Has anyone any suggestions on making it so that updates are quick and non-flickering???

- M. Python
 
use a client side xml javascript to write to the page every so often, it wont flicker because it's not refreshing client side, yet will refresh via the javascript as fast/often as you need to, just port the output via an xml using asp.

if you need a little more in depth info on this i'll happily post some code.

[thumbsup2]DreX
aKa - Robert
 
DreXor,

I know what xml is, but never get around to play with it. But now I guess is the time to get rollin with XML! If you still don't mind, can you give me some insite (code posting) or whatever you can on this subject/project? I'll thank you in advance.... Thanx a mula!!
 
well .. this is going to be a lengthy post i can tell :) ... Tarwn/onpnt if you happen to get a chance to look this over in depth, perhspa some changes could be recommended .. this was something i threw together a while ago to enable some form of web chat ..

Chat.ASP

the Hex/urlencoding stuff is because the messages are handled via the JS in the page, and hence used via querystring, and things like % tend to make things a little grumpy.
Code:
<%
' Response.buffer = True
'browser detection, never played with this long enough to make it cross browser happy.
Set objBCap = Server.CreateObject("MSWC.BrowserType") 
    If InStr(Request.ServerVariables("HTTP_USER_AGENT"), "MSIE 6") then
        Browser = "IE6"
    ElseIf objBCap.Browser = "IE" And CInt(objBCap.Version) >= 3 Then 
        Browser = "IE"
    ElseIf objBCap.Browser = "Netscape" And CInt(objBCap.Version) >= 3 Then 
        Browser = "Netscape"
    Else ' this if for opera etc
        Browser = "Other"
    End If 

 ACTION = Request("act")
 
 if ACTION = "logout" then
 	Session.abandon
 	response.redirect "default.asp"
 end if
 
 if Session("user") = "" then
 	response.redirect "default.asp"
 end if
ColorArr = Split("gray,black,purple,magenta,red,orange,gold,brown,green,blue,slateblue",",") 
DefColor = 1
CalcLen = 256 - 41 - Len(Session("User"))
%>
<html>
<head>
<title>DreX's WebChat</title>
<style>
.handme {
cursor: hand;
font-family: Tahoma;
font-size: 8px;
}
.text
{
font-family: Tahoma;
font-size: 12px;
color: blue;
}
.messagetext
{
font-family: Tahoma;
font-size: 12px;
color: <=ColorArr(DefColor)%>;
}
.entry
{
font-family: Tahoma;
font-size: 12px;
border:solid;
border-width:1;
background:white;
}
</style>

<script type="text/javascript">
var msgpass
var msgstr
var refpoint

function scrollToBottom (element) {
  if (document.all)
    element.scrollTop = element.scrollHeight;
}

function processXML() 
{
xmlDoc=new ActiveXObject("microsoft.xmldom");
xmlDoc.async=false;
xmlDoc.load("responsexml.asp");

makeDocument();
}

function appendXML() 
{
if ( document.sender.msg.value == "" )
{
return false;
}
strvar = document.sender.msg.value
refpoint = strvar.lastIndexOf(' ')
if (refpoint > 0 && strvar.length==<%=CalcLen%>)
{
msgpass = strvar.substring(refpoint+1,strvar.length);
document.sender.msg.value = strvar.substring(0,refpoint);
}
else
{
msgpass="";
}

xmlDoc.load( "responsexml.asp?act=add&col=" + document.sender.color.value + "&name="+ URLEncode(document.sender.name.value) +"&msg="+ URLEncode(document.sender.msg.value) );
document.sender.msg.value = msgpass;
document.sender.msg.focus();

}

function makeDocument() 
{
tableStr='<table border="0" class="text">';
messages=xmlDoc.documentElement.childNodes;
for ( i=0;i<messages.length;i++ )
tableStr+='<tr><td class="text" nowrap align="right" valign="top">'+messages[ i].childNodes[1].text+':</td><td class="messagetext" align="left" valign="top">'+messages[ i].childNodes[2].text+'</td></tr>';
tableStr+='</table>';
document.getElementById( "mainTable" ).innerHTML = tableStr;

Timer();
}

function Timer() 
{
setTimeout( "processXML();",5000 );
}

function OpenClose(url,winid)
{
      winvar = window.open(url,winid,'menubar=no,scrollbars=no,resizable=yes,width=200,height=200');
      winid.focus();
}
function URLEncode(formobj)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = formobj;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" +
				        "(URL encoding only supports 8-bit characters.)\n" +
						"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};
function colorchanger(colorval)
{
    document.sender.msg.style.color = colorval;
    labelobj.style.color = colorval;
    maintable.style.color = colorval;
    document.body.style.scrollbarBaseColor = colorval;
    document.sender.sendbtn.style.color = colorval;
    document.body.style.scrollbarBaseColor = colorval;
}

function doKey(keypressed)
{
  Key=keypressed.keyCode;
  if (Key==13)
  {
    appendXML();
    return false;
  }
  if (document.sender.msg.value.length==<%=CalcLen%>)
  {
    appendXML();
    return false;
  }
}

</script>

</head>
<body onload="processXML();colorchanger('<%=ColorArr(DefColor)%>');document.sender.msg.focus();" bgcolor="white" onclick="document.sender.msg.focus();" onUnload="window.open('logout.asp?name=<%=Server.URLEncode(Session("User"))%>','logout','status=no,menubar=no,location=no,scrollbars=no,resizable=no,width=75,height=75');" onfocus="document.sender.msg.focus();">
<script language="javascript">
    <!--
    var winh = 200;
    var winw = 425;
        window.resizeTo(winw,winh);
        self.moveTo(screen.availWidth - winw,screen.availHeight - winh);
        self.focus();
        alert('You will be asked if you\nwant to close a window\n          if so,\n      select YES');
        opener.close();
    // -->
</script>
<div style="border:1px solid; width:98%; height:75%; overflow-y:auto; overflow-x:auto; background:white;" id="maintable" name="maintable">
<table valign="top" align="left" cellpadding="0" cellspacing="0">
	<tr>
		<td valign="top"><div id="mainTable"> </div></td>
	</tr>
</table>
</div>
<table border="0" cellpadding="2" cellspacing="0">
	<tr>
		<td valign="baseline" align="right"><div id="labelobj" style="font-family: Tahoma;font-size: 12px;" valign="top"><%=Session("user")%>:</div></td>
		<td valign="top" align="left" nowrap>
            <form name="sender" onsubmit="return false;">
                <input type="hidden" name="name" value="<%=Server.HTMLEnCode(Session("user"))%>">
                <input type="hidden" name="color" value="<%=DefColor+1%>">
                <input type="text" name="msg" size="<%=55-Len(Session("user"))%>" maxlength="<%=CalcLen%>" onKeyPress="return doKey(event);" class="entry">&nbsp;
                <input type="button" value="Send" onclick="appendXML();" class="entry" id="sendbtn" name="sendbtn">
        </td>
        <td></form></td>
    </tr>
    <tr>
        <td colspan="3" valign="top" align="left" nowrap>
            <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td align="left"><%Colors%></td>
                    <td align="right">
                        <img src="/images/smileys/1.gif" border="0" onclick="OpenClose('smileys.asp','smileys');" class="handme">
                        <img src="/images/smileys/16.gif" border="0" onclick="OpenClose('smileys.asp?all=yes','smileys');" class="handme">
                        <img src="/images/smileys/06.gif" border="0" onclick="OpenClose('connected.asp','users');" class="handme">
                        &nbsp;&nbsp;&nbsp;
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>
<%
Function Colors()
Squaresize = 15
%>
<table bordercolor="yellow" border="1" cellspacing="0" cellpadding="2">
<tr>
<%
    For colorval = 0 to ubound(colorarr)
%>
<td bgcolor="<%=ColorArr(colorval)%>" onClick="colorchanger('<%=colorarr(colorval)%>');document.sender.color.value='<%=Colorval+1%>';" height="<%=squaresize%>" width="<%=squaresize%>"class="handme">&nbsp;</td>
<%
    next
%>
</tr>
</table>
<%
End Function
%>


msgasp.xml
this page handles the messages so that chat can pull them and display them ( this is asp enabled xml extiontion to fool the browser into thinking it's pure xml

this is watered down to save space, basically whatever means to make the xml to display for the chat page..
Code:
<%Response.Buffer=True%><?xml version="1.0"?>
<messages>
<%
' blah blah cutoff
do while not rs.eof
%>
    <note>
        <time><%=Server.HTMLEncode(RS("Now"))%></time>
        <from><%=Server.HTMLEncode(RS("User"))%></from>
        <body><%=Server.HTMLEncode("<font color=""" & ColorParse(RS("color")) & """>" & RS("Message") & "</font>")%></body>
    </note>
<%
Response.Flush
RS.MoveNext
Loop
Set RS = nothing
Con.Close
Set Con = nothing
%>
</messages>

colorparse in the above code is a reverse form of colors from the first block of code.

and responsexml.asp just handles the arrivals/departures/and just adds the messages to the DB for fetching, the db in it's simplest form is a table called chat with user/message/color/timestamp(now)
Code:
<%

	ACTION = Request("act")
	USER = Request("name")
	BODY = Request("msg")
	color = Request("col")
    if color = "" then color="2"
	
	if ACTION = "add" then
	
		if USER <> "" AND BODY <> "" then
            Set con = Server.CreateObject("ADODB.Connection")
        	Con.open "DSN=Chat;"
        
        	sql = "insert into [chat]([user],[message],[ip],[color]) values('" & SQLQuotes(User) & "','" & SQLQuotes(Body) & "','" & Trim(Request.ServerVariables("REMOTE_ADDR")) & "'," & color & ")"
            Set RS = Con.Execute(sql)
        
        	Set RS = nothing
        	Con.close
            Set Con = Nothing
		end if
	
	end if

	Response.redirect("msgasp.xml")

Function SQLQuotes(Value) 'replaces out single quotes in SQL statements for when you're sending data back to SQL Serv
On Error Resume Next
    SQLQuotes = Trim(Replace(Value,"'","''"))
End Function
%>

the other pages are just extraneous stuffs, like connected just lists users that havent logged out with a now()-last post timestamp to display idle time, smileys is just a table/db/reference to image filename to keycodes to translation bunk for smiley handling.

oh .. and almost forgot .. logout.asp
Code:
<%
if Request("name") <> "" then
    randomize
    g_random=int(rnd*6)+1

' these are just random exit strings for the db, little added flavor when leaving.
    select case g_random
        case "1"
            exitmsg ="ran with scissors too often"
        case "2"
            exitmsg ="hides in the corner so as not to be found"
        case "3"
            exitmsg ="fell off the castle wall"
        case "4"
            exitmsg ="gaps, chokes, then oddly, explodes"
        case "5"
            exitmsg ="spouts wings from their @$$ and flies away"
        case else
            exitmsg ="hath run for their life"
    end select


    Set con = Server.CreateObject("ADODB.Connection")
	Con.open "DSN=Chat;"
	sql = "insert into [chat]([user],[message],[ip],[color]) values('" & replace(Request("name"),"'","''") & "','" & exitmsg & "...(" & formatdatetime(now(),vbLongTime) & ")','" & Trim(Request.ServerVariables("REMOTE_ADDR")) & "',1)"
    Set RS = Con.Execute(sql)
	sql = "delete * from [connected] where [user] = '" & replace(Request("name"),"'","''") & "'"
    Set RS = Con.Execute(sql)
	Set RS = nothing
	Con.close
    Set Con = Nothing
    session.abandon()
    session("User") = ""
 end if
%>
<html>
<body>
<script language="javascript">
 window.close();
 opener.location('default.asp');
</script>
</body>
</html>

[thumbsup2]DreX
aKa - Robert
 
DreX,

1st of all, I appreciate the posting.. Thanx!

I've tested the code given there; And the only downside (which is the most important here) is I can't see any chat going on. The messages are not posting to the "mainTable"; It's empty (going blind now :). I'm able to get the msgs to the database, but getting it on web display's a bummer!

I think it has to with the msgasp.xml. Does that file need a ADODB declaration -or- does it retrieve from the responsexml.asp? Now i noticed you mentioned it's an asp enabled file... do i need to configure its MIME in IIS?

P.S. U're right... it's beginning to be a lenghty post!
 
Drex, I don't think those xmlDoc.load("responsexml.asp") statements are going to work the way you want them to...?
Wouldn't that be a call to load a local file (on the client) called responsexml.asp?

The last time I dealt with remote XML in javascript I had to use the XMLHTP object (which is a lot of fun cross-browser, let me tell you).


Also, on the browser detect thing, that object uses a lookup file in your system directory...i know I have posted links for updated copies somewhere before and the name and location, but I can't remmber it now. You may want to hit the search with "BrowserType". The file name is right on the tip of my tongue, but it's not ...heh, it's called browscap.ini and it's located in WINNT\system32\inetsrvI still don't remember the guy's site I downloaded mine from, but it should be here in the forums somewhere (MS is slack about updating it).

-T

01000111 01101111 01110100 00100000 01000011 01101111 01100110 01100110 01100101 01100101 00111111
Need an expensive ASP developer in the North Carolina area? Feel free to let me know.


 
nah this code is functional, i use it frequently to talk with my gf at home from work :p

monty, yes msgasp.xml does have a connection in it, i truncated that stuff out to shorten the post, but the info is still the same.. dsn=chat, whatever, select top 100 * from chat where timestamp < now-.25 ..... or something of the likes, basically just something to return you your displayable recordset, since you're just getting it operational, just use a select * from chat

another thing, this has only been tested/used in IE 5+

as i noted in the code post, i havent had time to sit back and tinker with it.

[thumbsup2]DreX
aKa - Robert
 
DreXor,

I've already included the connection in the msgasp.xml, and it's still a no show. That darn messages just won't show up on the web interface! Well, I'm going to explore it more and see if can get this javascript/xml idea working. Wish me luck!.
 
i will attempt to put this up for download online temporarily, unfortunately we're not allowed to share email addresses through this forum, so i cant request/email the code to you.

please note that the msgasp.xml must be enabled in the web properties under configuration to have .xml enabled as an .asp extention.

when i get this zipped p and available for download i'll post it up on geocities or my personal server temporarily

[thumbsup2]DreX
aKa - Robert
 
ps, as mentioned before, dont forget in the subfolder where this will be housed.. to add .xml as a .asp extention, otherwise the msgasp.xml will not output the raw data form the db as xml.. you'll just have a fubar xml file that will fail the chat display.

[thumbsup2]DreX
aKa - Robert
 
oh, and if you happen to "spiff" this up some, like adding private msgs or chat rooms, etc, i would love to add the added functionality to it, just haven't made it that far yet :)

other features already in the code :
client side cleanup of special characters in passing the submit.

due to querystring length limits there's a validation of length when typeing, when the box gets "too full" it'll auto post and allow you to keep typing, breaking the text at the last word spacing.

selected font color is depicted in the input box, the text frame, and scroll bars.

resizing the window will, for the most part, resize the text frame as well

also adding a smileys.zip to the same location above, noticed in the zip file there's no images, and without those the broken images, look pretty dumb.

let me know if i can help in any other way.


[thumbsup2]DreX
aKa - Robert
 
DreX,

With those x-tra files, some asp & Sql query modifications, it works wonders!

Got one question though. In msgasp.xml,
"SELECT * FROM Chat WHERE (Now > GetDate()-" & 20/60/24 & ") order by Now DESC".... What date is 20/60/24?? I've tested the query straight from SQL Server and it returns nothing (Though it works fine w/ the web app). I'm also trying to get the messages entered to popup at the bottom of the chat screen (rather than the top).

Thumbs up for the DreXor!
 
Ok i got the msgs to pop at the bottom, but the focus is always at the top.. Meaning dat I've to scroll down to see the last message entered. Hmm..
 
you could always add a scroll to bottom with a little added java, i ried that before and it made it "jiggle" a little so i took it back out.. also the date you were asking about [lol] if you look at it sideways... it's to give you the decimal value of 20 minutes in the form of days... 20 of 60 minutes of 24 hours..

hopefully it's along the lines you were looking for.

[thumbsup2]DreX
aKa - Robert
 
Fellas
I tried setting up & running the webchat.zip files on my IIS and I keep getting the exclamation mark error on my browser's status "Line: 79 Char:1 Error:Object required Code: 0 URL: Now I am hunching its related to the msgasp.xml file which should be asp enabled, but how exactly did you guys enable it?

IIS --> Website --> Right-Clicked msgasp.xml --> Properties --> HTTP Headers --> File Types --> New Type --> ???
I know its something very simple, but what exaclty do I enter for "Associated extensions", and for "Content Type (MIME)"?
 
actually recent fiddling with the files has led me to a discovery, the .xml extention can be renamed to .asp, and the .xml asp enabling can be removed. my original thoughts was the parsing of xml data, this was converted to allow a DB in the middle of it without having to add another page or two to do it then redirect. it appears the parsing doesn't care what filetype the origin is from, just the output.

so msgasp.xml can be renamed to msgs.asp ( personally i would rename it to xmlmsgs.asp , due to it being xml formatted output ) then in other files in the pack, replace msgasp.xml for the renamed filename.

later today i'll attempt to update the zip file to reflect these changes.


[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
 
ok .. updated and uploaded to geocities the updated version of webchat.zip.


smileys.zip has been deleted, and wrapped into webchat.zip, all path statements have been updated, etc.

bascially i did a local test on a seperate machine with IIS installed.

steps followed :
downloaded file to desktop

right clicked zip file and extracted to desktop/webchat

right clicked webchat folder - properties, web sharing tab, enabled, and virtual named folder "chat"

opened ie to :
signed in and everything ran fine.

hopefully this will be the same for you all that may have had problems with the prior zip package.

thanks, and i keep this thread on notify should there be futher questions/comments

[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
 
i havent had much chance to play with this code in a while other than the updates i made today ( Oct-11-04 ) i will look things over and attempt to overhaul this code soon, attempt to make a consolidated include file with public variables like ListAscending ( post flow bottom to top / top to bottom ) with auto scroll features, universal color schemes and/or user based color schemes.

possibly work into the mix seperate chat rooms, private chat rooms, and user -> user msging, user registrations etc.

will post again to this thread after the bundle has been overhauled, those of you that may have downloaded it and are still on notify, this will allow you to get the newest revision when it's available.

thanks for all your patience and feedback on this side project.


[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top