<%@ CODEPAGE=65001 %><%'///'// AJAX Chat Room'// 作 者: duduwolf'// 版权所有: 嘟嘟老窝(http://www.duduwolf.com/)'// 技术支持: duduwolf@hotmail.com'///Option Explicit'On Error Resume NextResponse.Buffer = true
Dim actact = Request("act")
Const CHAT_SESSION = "CHAT_ROOM_AJAX_SESSION"Const CHAT_MSG = "CHAT_ROOM_AJAX_MSG"Const CHAT_NICKNAME = "CHAT_ROOM_AJAX_NICKNAME"
Dim SessionArray, MsgArray, i, onlineCount
If Not IsEmpty(Application(CHAT_SESSION)) ThenApplication.LockSessionArray = Split(Application(CHAT_SESSION), ",")MsgArray = Split(Application(CHAT_MSG), Chr(13))Application.UnLockElse'Application.Lock'Application(CHAT_SESSION) = Session.SessionID'Application.UnLockEnd If
Function FindArray(Arr, Var)If IsEmpty(Arr) Or IsNull(Arr) Then FindArray = -1Exit FunctionEnd If
If UBound(Arr) = 0 ThenFindArray = -1ElseFor i = 0 To UBound(Arr)If Arr(i) = Var Then FindArray = iExit FunctionEnd IfNextEnd If
FindArray = -1End Function
If Request.ServerVariables("REQUEST_METHOD") = "POST" ThenResponse.ClearResponse.ContentType = "text/xml"
Dim xmlHead, xmlFoot, msg
xmlHead = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?><chatroom online=""" & onlineCount & """ self=""" & Session(CHAT_NICKNAME) & """>"xmlFoot = "</chatroom>"
If act = "sendChat" ThenIf IsNull(SessionArray) Or IsEmpty(SessionArray) Then Response.End
msg = "<msg nick=""" & Request("nick") &""">" & Request("msg") & "</msg>"For i = 0 To UBound(SessionArray)If SessionArray(i) <> Session.SessionID ThenMsgArray(i) = MsgArray(i) & Chr(10) & msgApplication.LockApplication(CHAT_MSG) = Join(MsgArray, Chr(13))Application.UnLockEnd IfNext
Response.Write xmlHeadResponse.Write "<msg nick=""" & Session(CHAT_NICKNAME) &""">" & Request("msg") & "</msg>"Response.Write xmlFoot
ElseIf act = "getChat" ThenDim pospos = FindArray(SessionArray, Session.SessionID)If pos > -1 ThenIf IsArray(MsgArray) ThenDim ArrIf MsgArray(pos) <> "" ThenResponse.Write xmlHeadArr = Split(MsgArray(pos), Chr(10))If Not IsEmpty(Arr) And UBound(Arr) >= 0 ThenFor i = 0 To UBound(Arr)Response.Write Arr(i)NextEnd IfResponse.Write xmlFootMsgArray(pos) = ""Application.LockApplication(CHAT_MSG) = Join(MsgArray, Chr(13))Application.UnLockEnd IfEnd IfEnd IfElseIf act = "login" ThenIf Len(Request("nick")) > 0 ThenDim nickArrIf Not IsEmpty(Application(CHAT_NICKNAME)) ThennickArr = Split(Application(CHAT_NICKNAME), Chr(10))If Not IsEmpty(nickArr) ThenFor i = 0 To UBound(nickArr)If nickArr(i) = Request("nick") ThenResponse.Write xmlHeadResponse.Write "<login nick=""" & Session(CHAT_NICKNAME) & """>昵称[" & Request("nick") & "]已经被其他用户选用,请更改昵称!</login>"Response.Write xmlFootResponse.EndEnd IfNextEnd IfEnd IfIf FindArray(SessionArray, Session.SessionID) = -1 ThenApplication.LockIf IsEmpty(SessionArray) Then Application(CHAT_SESSION) = Session.SessionIDSessionArray = Split(Application(CHAT_SESSION), ",")Application(CHAT_MSG) = ""MsgArray = Split(Application(CHAT_MSG), Chr(13))Application(CHAT_NICKNAME) = Request("nick")ElseApplication(CHAT_SESSION) = Join(SessionArray, ",") & "," & Session.SessionIDSessionArray = Split(Application(CHAT_SESSION), ",")Application(CHAT_MSG) = Join(MsgArray, Chr(13)) & Chr(13) & ""MsgArray = Split(Application(CHAT_MSG), Chr(13))Application(CHAT_NICKNAME) = Application(CHAT_NICKNAME) & Chr(10) & Request("nick")End If
Application.UnLock
If IsNull(SessionArray) Or IsEmpty(SessionArray) Then Response.End
For i = 0 To UBound(SessionArray)If SessionArray(i) <> Session.SessionID ThenMsgArray(i) = MsgArray(i) & "<system>用户[" & Request("nick") & "]进入了聊天室</system>" & Chr(10)Application.LockApplication(CHAT_MSG) = Join(MsgArray, Chr(13))Application.UnLockEnd IfNextEnd IfSession(CHAT_NICKNAME) = Request("nick")
Response.Write xmlHeadResponse.Write "<login nick=""" & Session(CHAT_NICKNAME) & """>OK</login><system>用户[" & Session(CHAT_NICKNAME) & "]进入了聊天室</system>"Response.Write xmlFootEnd IfElseIf act = "logout" ThenDim str, str1, str2If Not IsEmpty(Application(CHAT_NICKNAME)) ThennickArr = Split(Application(CHAT_NICKNAME), Chr(10))End If
For i = 0 To UBound(SessionArray)If SessionArray(i) <> Session.SessionID ThenIf i = 0 Thenstr = SessionArray(i)str1 = MsgArray(i)str2 = nickArr(i)Elsestr = str & "," & SessionArray(i)str1 = str1 & Chr(10) & MsgArray(i) & Chr(13) & "<system>用户[" & request("nick") & "]退出了聊天室!</system>"str2 = str2 & Chr(10) & nickArr(i)End If
End IfNext
Application.LockApplication(CHAT_SESSION) = strApplication(CHAT_MSG) = str1Application(CHAT_NICKNAME) = str2Application.UnLockEnd If
ElseIf act = "script" ThenResponse.ClearResponse.ContentType = "text/javascript"%>
//*********************************************************// 目的: AJAX类// 输入: 无// 返回: 返回XMLHttp对象// 例子: var myConn = new XHConn();//// if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");//// var fnWhenDone = function (oXML) { alert(oXML.responseText); };//// myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);////*********************************************************function XHConn(){var xmlhttp = false, bComplete = false;try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e) { try { xmlhttp = new XMLHttpRequest(); }catch (e) { alert(e);xmlhttp = false; }}}if (!xmlhttp) return null;this.connect = function(sURL, sMethod, sVars, fnDone, parObj){if (!xmlhttp) return false;bComplete = false;sVars = (sVars == '') ? Math.random() : sVars + '&' + Math.random( );sMethod = sMethod.toUpperCase();
try {if (sMethod == "GET"){xmlhttp.open(sMethod, sURL + '?' + sVars, true);xmlhttp.setRequestHeader("Content-Type", "text/html;charset=GB2312");sVars = "";}else{xmlhttp.open(sMethod, sURL, true);xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");}xmlhttp.onreadystatechange = function(){if (xmlhttp.readyState == 4 && !bComplete){bComplete = true;fnDone(xmlhttp, parObj);}};xmlhttp.send(sVars);}catch(z) { return false; }return true;};return this;}var URL, VAR;//*****************************************************// 聊天类//*****************************************************var ChatRoom = function(obj, parentWin, w, h) {
this.style = {width : w ? w : 500, //宽height : h ? h : 300 //高}
this.obj = obj; //聊天类的实际DOM名称this.parentWin = parentWin ? parentWin : null; //聊天窗口的父级DOM对象this.input = null; //聊天信息输入框this.chatWin = null; //聊天信息显示DOM对象this.login = null; //昵称输入框this.loginBtn = null; //登陆(退出)按钮this.conn = new XHConn(); //AJAX对象if (!this.conn) alert("XMLHTTP not available. Try a newer/better browser.");this.serverUrl = null; //服务端请求路径this.can = false; //聊天室初始化是否正常
this.nickName = '匿名'; //登陆昵称this.onlineCount = -1; //在线人数
this.createChatRoom();
VAR = 'act=logout&nick=' + this.nickName;URL = this.serverUrl;
if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "onbeforeunload", this.logout1, false );
// IE else if ( typeof window.attachEvent != "undefined" ) {window.attachEvent( "onbeforeunload", this.logout1);}
else {if ( window.onbeforeunload != null ) {var oldOnunload = window.onbeforeunload;window.onbeforeunload = function ( e ) {oldOnunload( e );this.logout1;};}else window.onbeforeunload = this.logout1;}
return this;}
//创建聊天相关的DOM对象ChatRoom.prototype.createChatRoom = function() {if (!this.parentWin || this.parentWin == null || typeof (this.parentWin) != 'object') {alert('无法加载聊天窗口,请查看调用代码是否正确');return;}
this.createStyle();this.parentWin.innerHTML = '请输入你的昵称:<input type="text" size="10"> <input type="button" οnclick="' + this.obj + '.loging();" value="登陆"><div class="chatroom"></div><input type="text" style="width:' + (this.style.width - 40) + ';" οnkeypress="if(event.keyCode==13)' + this.obj + '.sendChat();"> <button οnclick="' + this.obj + '.sendChat();">发送</button>';this.login = this.parentWin.getElementsByTagName('input')[0];this.loginBtn = this.parentWin.getElementsByTagName('input')[1];this.input = this.parentWin.getElementsByTagName('input')[2];this.chatWin = this.parentWin.getElementsByTagName('div')[0];
var o = document.getElementsByTagName("script");for (var i = 0; i < o.length; i++) {len = o[i].src.indexOf('chatRoom.asp');if (len > -1) {this.serverUrl = o[i].src.substring(0, len + 12);break;}}
if (!this.serverUrl || this.serverUrl.length == 0) {alert('程序初始化出错');retur;}
this.can = true;
this.getChat(true);}
//创建相关样式表ChatRoom.prototype.createStyle = function() {document.write('<style>');document.write('.chatroom{');document.write('width:' + this.style.width + 'px;');document.write('height:' + this.style.height + 'px;');document.write('overflow-y:scroll;');document.write('border:1px solid #000');document.write('margin:10px;');document.write('padding-bottom:50px;');document.write('}');document.write('.chatroom li{');document.write('list-style-type:none;');document.write('padding:3px 0 3px 0;');document.write('}');document.write('.self{');document.write('color:#269926;');document.write('}');document.write('</style>');}
//发送消息ChatRoom.prototype.sendChat = function() {if (!this.can) return;if (!this.logined) {alert('请先登陆!');this.login.focus();return;}
var msg = this.input.value;if (msg && msg.length > 0) {msg = 'act=sendChat&msg=' + this.encode(msg) + '&nick=' + this.nickName;this.conn.connect(this.serverUrl, 'POST', msg, this.fnResponse, this);this.input.value = '';}}
//从服务端取得最新的聊天信息ChatRoom.prototype.getChat = function(first) {if (!this.can) return;if (!this.logined && !first) return;var sVar = "act=getChat";this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse, this);var obj = this;window.setTimeout(function(){obj.getChat();}, '1000');}
//登陆聊天室ChatRoom.prototype.loging = function() {if (this.loginBtn.value == '退出') {this.logout();return;}
if (!this.can) return;if (this.login.value.length == 0) {alert('请输入昵称!');this.login.focus();return;}if (this.login.value.length > 20) {alert('昵称太长了吧,最多十个汉字!');this.login.focus();this.login.select();return;}
var sVar = 'act=login&nick=' + this.login.value;this.nickName = this.login.value;VAR = 'act=logout&nick=' + this.nickName;this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse, this);}
//退出聊天室ChatRoom.prototype.logout = function() {if (!this.can) return;if (!this.logined) return;var sVar = 'act=logout&nick=' + this.nickName;this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse, this);this.logined = false;this.loginBtn.value = '登陆';}
//退出聊天室1ChatRoom.prototype.logout1 = function() {if (document.getElementsByTagName("INPUT")[1].value == '退出') {var conn = new XHConn();conn.connect(URL, 'POST', VAR, function(){}, this);}}
//编码字符串ChatRoom.prototype.encode = function(str) {return encodeURIComponent(str);}
//处理AJAX服务端返回的代码ChatRoom.prototype.fnResponse = function(oXml, parObj) {//if (oXml.responseText.length > 0) alert(oXml.responseText);var xmlDoc = oXml.responseXML.documentElement;if (xmlDoc && typeof xmlDoc == 'object') {parObj.parseXML(xmlDoc);}}
//解析服务端传回的XML代码,并进行相应操作ChatRoom.prototype.parseXML = function(xmlDoc) {var attList = xmlDoc.attributes;if (attList && attList.length == 2 ) {if (attList[0].name == 'online')this.onlineCount = attList[0].value;if (attList[1].name == 'self')this.self = attList[1].value;
if (this.self.length > 0) this.logined = true;}
var arr = xmlDoc.childNodes, newChat, str;for (var i = 0; i < arr.length; i++) {if (arr[i] && arr[i].nodeName == 'msg' && arr[i].childNodes[0].nodeType == 3 && arr[i].childNodes[0].nodevalue.length > 0) {
newChat = document.createElement('LI');this.chatWin.appendChild(newChat);str = '';
if (arr[i].attributes[0].name == 'nick') {if (arr[i].attributes[0].value == this.self)str += '<span class="self">你说:</span>';elsestr += arr[i].attributes[0].value + '说:';
str += arr[i].childNodes[0].nodevalue;
newChat.innerHTML = str;this.chatWin.scrollTop = this.chatWin.scrollHeight;}} else if (arr[i] && arr[i].nodeName == 'system' && arr[i].childNodes[0].nodeType == 3 && arr[i].childNodes[0].nodevalue.length > 0) {
newChat = document.createElement('LI');this.chatWin.appendChild(newChat);str = '<span style="color:blue">系统:</span>' + arr[i].childNodes[0].nodevalue;newChat.innerHTML = str;this.chatWin.scrollTop = this.chatWin.scrollHeight;} else if (arr[i] && arr[i].nodeName == 'login' &&arr[i].childNodes[0].nodeType == 3 && arr[i].childNodes[0].nodevalue.length > 0) {if (arr[i].childNodes[0].nodevalue == 'OK') {this.logined = true;this.loginBtn.value = '退出';this.getChat();} else {alert(arr[i].childNodes[0].nodevalue);}}}}
<%End If%>