【80酷酷网 诚交80后的朋友】

2013 年 12 月 8 日5880

  ajax|聊天室<% CODEPAGE=65001 %><%
'///////////////////////////////////////////////////////////////////////////////
'// AJAX Chat Room
'// 作 者: duduwolf
'// 版权所有: 嘟嘟老窝()
'// 技术支持: duduwolfhotmail.com
'///////////////////////////////////////////////////////////////////////////////
Option Explicit
'On Error Resume Next
Response.Buffer = true

Dim act
act = 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)) Then
Application.Lock
SessionArray = Split(Application(CHAT_SESSION), ",")
MsgArray = Split(Application(CHAT_MSG), Chr(13))
Application.UnLock
Else
'Application.Lock
'Application(CHAT_SESSION) = Session.SessionID
'Application.UnLock
End If

Function FindArray(Arr, Var)
If IsEmpty(Arr) Or IsNull(Arr) Then
FindArray = -1
Exit Function
End If

If UBound(Arr) = 0 Then
FindArray = -1
Else
For i = 0 To UBound(Arr)
If Arr(i) = Var Then
FindArray = i
Exit Function
End If
Next
End If

FindArray = -1
End Function

If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
Response.Clear
Response.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" Then
If 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 Then
MsgArray(i) = MsgArray(i) & Chr(10) & msg
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
Next

Response.Write xmlHead
Response.Write "<msg nick=""" & Session(CHAT_NICKNAME) &""">" & Request("msg") & "</msg>"
Response.Write xmlFoot

ElseIf act = "getChat" Then
Dim pos
pos = FindArray(SessionArray, Session.SessionID)
If pos > -1 Then
If IsArray(MsgArray) Then
Dim Arr
If MsgArray(pos) <> "" Then
Response.Write xmlHead
Arr = Split(MsgArray(pos), Chr(10))
If Not IsEmpty(Arr) And UBound(Arr) >= 0 Then
For i = 0 To UBound(Arr)
Response.Write Arr(i)
Next
End If
Response.Write xmlFoot
MsgArray(pos) = ""
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
End If
End If
ElseIf act = "login" Then
If Len(Request("nick")) > 0 Then
Dim nickArr
If Not IsEmpty(Application(CHAT_NICKNAME)) Then
nickArr = Split(Application(CHAT_NICKNAME), Chr(10))
If Not IsEmpty(nickArr) Then
For i = 0 To UBound(nickArr)
If nickArr(i) = Request("nick") Then
Response.Write xmlHead
Response.Write "<login nick=""" & Session(CHAT_NICKNAME) & """>昵称[" & Request("nick") & "]已经被其他用户选用,请更改昵称!</login>"
Response.Write xmlFoot
Response.End
End If
Next
End If
End If
If FindArray(SessionArray, Session.SessionID) = -1 Then
Application.Lock
If IsEmpty(SessionArray) Then
Application(CHAT_SESSION) = Session.SessionID
SessionArray = Split(Application(CHAT_SESSION), ",")
Application(CHAT_MSG) = ""
MsgArray = Split(Application(CHAT_MSG), Chr(13))
Application(CHAT_NICKNAME) = Request("nick")
Else
Application(CHAT_SESSION) = Join(SessionArray, ",") & "," & Session.SessionID
SessionArray = 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 Then
MsgArray(i) = MsgArray(i) & "<system>用户[" & Request("nick") & "]进入了聊天室</system>" & Chr(10)
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
Next
End If
Session(CHAT_NICKNAME) = Request("nick")

Response.Write xmlHead
Response.Write "<login nick=""" & Session(CHAT_NICKNAME) & """>OK</login><system>用户[" & Session(CHAT_NICKNAME) & "]进入了聊天室</system>"
Response.Write xmlFoot
End If
ElseIf act = "logout" Then
Dim str, str1, str2
If Not IsEmpty(Application(CHAT_NICKNAME)) Then
nickArr = Split(Application(CHAT_NICKNAME), Chr(10))
End If

For i = 0 To UBound(SessionArray)
If SessionArray(i) <> Session.SessionID Then
If i = 0 Then
str = SessionArray(i)
str1 = MsgArray(i)
str2 = nickArr(i)
Else
str = str & "," & SessionArray(i)
str1 = str1 & Chr(10) & MsgArray(i) & Chr(13) & "<system>用户[" & request("nick") & "]退出了聊天室!</system>"
str2 = str2 & Chr(10) & nickArr(i)
End If

End If
Next

Application.Lock
Application(CHAT_SESSION) = str
Application(CHAT_MSG) = str1
Application(CHAT_NICKNAME) = str2
Application.UnLock
End If

ElseIf act = "script" Then
Response.Clear
Response.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" value="登陆"><div></div><input type="text" onkeypress="if(event.keyCode==13)' + this.obj + '.sendChat();"><button >发送</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 = '登陆';
}

//退出聊天室1
ChatRoom.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>你说:</span>';
else
str += 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>系统:</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%>

上一篇:AJAX指南----操作XML 下一篇:AJAX技术图解

0 0