ajax聊天室(JSP版)6

原创 2007年09月20日 22:24:00

现在剩下JSP页面的HTML代码和JS代码了。直接贴代码,哪天用到了可以回头看看。

chat.js文件,用到了Prototype.js

/**
 *ajax聊天室js代码
 *聊天室version1.0
 *2007-6
 */
 
    var xhrGetMessages=null;
    var xhrListUsersInRoom=null;
    var defaultInterval=2000;
    var getMessagesInterval=2000;
    var getUsersInterval=4000;
    //最大延迟时间
    var maxInterval=4*1000;
    var delayEnabled=false;
    var delay=2;
   
    var getMessageUrl = "/chatroom/getMessage";
    var getUsersUrl ="/chatroom/getUserList";
    var sendMessageUrl="/chatroom/sendMessage";
    //保存上一次聊天信息,防止恶意发信息
    var oldSendMsg="";
   
    //初始化
    function init()
    {
       setTimeout("getMessages()", 2000);
       setTimeout("listUsers()", 3000);
    }
 
 
    //发送聊天信息
    function sendMessage() {
       var inputText=fullTrim($("userInput").value);
        if (inputText != "" && oldSendMsg!=inputText) {
           oldSendMsg=inputText;
           var toSomebody=""+$('user').value;
           if($('user').value=="all")toSomebody="所有人";
           $("content").innerHTML+="我对"+toSomebody+": "+inputText+"<br>";
           $('sendButton').disabled=true;
           //varurl="sendMessage";
           var params="to="+$('user').value+"&content=" + inputText;
           $("userInput").value="";
           var myAjax = new Ajax.Updater({success: 'tips'},sendMessageUrl,{method: 'get',parameters: params,onFailure: errorReport});
           $('sendButton').disabled=false;
        }else
       {
           alert("请不要连续发送相同信息");
       }
        returnfalse;
    }
 
    //错误提示
    function errorReport()
    {
       alert('Sorry. There was an error.');
    }
 
    function selectFont(elem)
    {
       $('content').style.fontSize=elem.value+"px";
    }
 
    function selectColor(elem)
    {
       $('content').style.color=elem.value;
    }
 
    //获取聊天信息
    function getMessages() {
       if (xhrGetMessages == null || xhrGetMessages.readyState == 0 ||
        xhrGetMessages.readyState == 4) {
        try {
              if (window.XMLHttpRequest){
                xhrGetMessages = new XMLHttpRequest();
              } else {
                xhrGetMessages = new ActiveXObject('Microsoft.XMLHTTP');
              }
              xhrGetMessages.onreadystatechange = getMessagesHandler;
              xhrGetMessages.open("get", getMessageUrl, true);
              xhrGetMessages.send(null);
            } catch(e) {
              alert("Error in getMessages() - " + e.message);
            return;
            }
          }
        timerGetMessages = setTimeout("getMessages()", getMessagesInterval);
        }
    //聊天信息处理方法
    function getMessagesHandler() {
       var newHTML      = "";
          if (xhrGetMessages.readyState == 4) {
            if (xhrGetMessages.status == 200) {
              msgDOM = xhrGetMessages.responseXML;
              root         = msgDOM.getElementsByTagName("messages")[0];
              messages     = root.getElementsByTagName("message");
              for (var i = 0; i < messages.length; i++) {
            message = messages[i];
                from = message.getElementsByTagName("from")[0].firstChild.nodeValue;
                date = message.getElementsByTagName( "date")[0].firstChild.nodeValue;
                msg = message.getElementsByTagName("content")[0].firstChild.nodeValue;
                newHTML += "[" + date + "] " + from + ": " + msg + "<br/>";
              }
             var content = $('content');
            if (newHTML != "") {
                    content.innerHTML += newHTML;
            }
           if(delayEnabled)
            {
              getMessagesInterval = getMessagesInterval<maxInterval ? getMessagesInterval*delay : defaultInterval;
            }
            if($('autoScrool').checked==true)content.scrollTop = 1000000;
            } else {
              alert("Error in getMessagesHandler() - " + xhrGetMessages.status);
            }
          }
 
    }
 
    //清空聊天内容
    function clearContent() {
     $('content').innerHTML="";
    }
 
    //清除空格
    function fullTrim(inString) {
      return (inString.replace(/^/s*(.*/S|.*)/s*$/, '$1'));
    }
 
    //获取用户列表
    function listUsers() {
      if (xhrListUsersInRoom == null || xhrListUsersInRoom.readyState == 0 ||
        xhrListUsersInRoom.readyState == 4) {
        try {
          if (window.XMLHttpRequest){
            xhrListUsersInRoom = new XMLHttpRequest();
          } else {
            xhrListUsersInRoom = new ActiveXObject('Microsoft.XMLHTTP');
          }
          xhrListUsersInRoom.onreadystatechange = listUsersInRoomHandler;
          xhrListUsersInRoom.open("get", getUsersUrl, true);
          xhrListUsersInRoom.send(null);
        } catch(e) {
          alert("Error in listUsersInRoom() - " + e.message);
        }
      }
        setTimeout("listUsers()", getUsersInterval);
    }
    //用户列表处理方法
    function listUsersInRoomHandler() {
        var newHTML = "";
       var userHTML="<select id='user' name='user'><option value='all'>所有人</option>";
        if (xhrListUsersInRoom.readyState == 4) {
           if (xhrListUsersInRoom.status == 200) {
              var msgDOM = xhrListUsersInRoom.responseXML;
              var root    = msgDOM.getElementsByTagName("users")[0];
              var users   = root.getElementsByTagName("user");
              for (var i = 0; i < users.length; i++) {
                  varname=users[i].getAttribute("name");
                  newHTML += name + "<br/>";
                  userHTML+="<option value='"+name+"'>"+name+"</option>";
              }
              if (newHTML!="") {
                  $("userList").innerHTML = newHTML;
                  $("to").innerHTML=userHTML+"</select>";
              }elseif(delayEnabled)
              {
                  getUsersInterval = getUsersInterval<maxInterval ? getUsersInterval*delay : defaultInterval;
              }
           }
/*         else{
               alert("ErrorinlistUsersInRoomHandler()-"+
               xhrListUsersInRoom.status);
           }
//*/
        }
    }
 
    Event.observe(window, 'load', init, false);

聊天室的外观很差,下面这个JSP文件也只是实现功能效果而已。
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${room.name}--聊天室</title>
<link href="css/chat.css" rel="stylesheet" type="text/css" />
<script src="js/prototype.js" language="JavaScript"
    type="text/javascript"></script>
<script type="text/javascript" src="js/chat.js"></script>
</head>
 
<body onunload="levae()">
<table width="100%" height="281" border="1" cellspacing="0"
    bordercolor="#FFFFFF">
    <tr>
       <td height="25" bordercolor="#FFFFFF" bgcolor="#FFFFFF"></td>
    </tr>
    <tr>
       <td valign="top">
       <table width="80%" height="376" border="1" align="center"
           cellspacing="0" bordercolor="#4A83EA">
           <tr bordercolor="#FFFFFF" bgcolor="#4A83EA">
              <td height="24" colspan="3"
                  style="color: #FFFFFF;text-align:center;">欢迎来到~~${room.name}~~
              </td>
           </tr>
           <tr>
              <td height="36" colspan="3" bgcolor="#DDE8FB">
              <div align="center">${room.notice}</div>
              </td>
           </tr>
           <tr>
              <td width="75%" height="246" colspan="2" bordercolor="#4A83EA">
              <div id="content" style="overflow:scroll;width:100%;height:100%;">&nbsp;</div>
              </td>
              <td width="19%" rowspan="3" bgcolor="#DDE8FB">
              <div id="userList" style="overflow:scroll;width:100%;height:100%;">&nbsp;</div>
              </td>
           </tr>
           <tr>
              <td height="38" bordercolor="#DDE8FB" bgcolor="#DDE8FB">字体<select
                  onchange='selectFont(this)'>
                  <script type="text/javascript">
    <!--
           for(var i=10;i<=34;i+=2)
           document.write("<option value='"+i+"' >"+i+"</option>");
 
    //-->
    </script>
              </select>颜色<select onchange='selectColor(this)'>
                  <%@ include file="inc/color_options.inc"%>
              </select><input type="checkbox" id="autoScrool" onclick="checkScroll(this)"
                  checked />自动滚屏</td>
              <td width="8%" bordercolor="#DDE8FB" bgcolor="#DDE8FB">
              <div align="right"><input type="button" name="clear"
                  value=" 清屏 " onclick="clearContent()"></div>
              </td>
           </tr>
           <tr>
              <td height="30" colspan="2" bordercolor="#4A83EA" bgcolor="#DDE8FB">
              你对<span id="to"><select id="user" name="user">
                  <option value="all">所有人</option>
              </select></span>说:<input type="text"
                  style="width:400px;background-color: #DDE8FB;" type="text"
                  id="userInput" name="userInput"
                  onkeyDown="javascript:if(event.keyCode==13)return sendMessage();" />
              <input name="sendButton" id="sendButton" type="button"
                  onclick="sendMessage();" value=" 发送 ">
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
           </tr>
 
       </table>
       </td>
    </tr>
</table>
</body>
<div id="tips" style="display:none;"></div>
</html>
其中包含color_options.inc文件,该文件内容如下:
<option value="#f0f8ff" style="color:#f0f8ff;">Alice Blue</option>
<option value="#faebd7" style="color:#faebd7;">Antique White</option>
...... 

登录界面也只是一个form表单而已。
<form id="form_" method="post" action="/chatroom/login">
<select id="roomName" name="roomName">
    <c:forEach items="${rooms}"var="room">
       <option value="${room.name}">${room.name}</option>
    </c:forEach>
</select><br>
<input type="text" name="userName" value="" />
<input type="submit" value="进入聊天室" />
</form>

这样基本把东西贴完了。下面说说功能扩展及其他。
对于判断用户离线使用HttpSessionBindingListener接口,其实不是十分可靠,可以在聊天室页面的onunload函数增加向服务台发出离开的信息。此外,也可以写一个后台守护进程,不断地检测用户的最后一次请求时间,若超时,则从用户列表中删除信息。
聊天室只有公聊私聊、改变字体大小和颜色、切换滚屏、清除屏幕等几个小功能。其实还可以增加屏蔽某人发言功能,实现起来也不难,但也要改最前面提到的三个类。仿照博客左边的这个聊天室,还可以增加一个休眠功能,直接在客户端的JS代码动手脚即可。
还是仿照博客左边的这个聊天室,增加发表情、图片、音乐等,实现起来也不会太难,主要是客户端写JS代码而已。当然,这个“而已”也是说说而已,暂时没兴趣玩这个了。
写了这么多,其实不是为了写什么教程入门文章,仅仅是想把自己做的一点小东西保存一下,以防哪天想要却找不到。好,现在就把全部代码上传。
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)