java服务器推的实现

转载自:http://vincent-yy.iteye.com/blog/427922

小型聊天室--DWR实现服务器推技术

      当看到DWR2也可以实现推技术之后,想尝试一下!
首先当官方上下载一个dwr的jar文件和commons-logging-1.1.1.jar
先从配置文件入手
web.xml
Xml代码 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app id="WebApp_ID" version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
 
    <!-- 以设置下格式固定,可复制使用 --> 
    <display-name>ajaxDWR</display-name> 
    <servlet> 
        <servlet-name>dwr-invoker</servlet-name> 
        <!-- 
            <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
        --> 
        <servlet-class> 
            org.directwebremoting.servlet.DwrServlet 
        </servlet-class> 
        <init-param> 
            <description>实现调试,在debug请设置为false</description> 
            <param-name>debug</param-name> 
            <param-value>true</param-value> 
        </init-param> 
        <init-param> 
            <description>使用服务器推技术(反转AJAX)</description> 
            <param-name>activeReverseAjaxEnabled</param-name> 
            <param-value>true</param-value> 
        </init-param> 
        <init-param> 
            <param-name> 
                initApplicationScopeCreatorsAtStartup 
            </param-name> 
            <param-value>true</param-value> 
        </init-param> 
        <init-param> 
            <param-name>maxWaitAfterWrite</param-name> 
            <param-value>100</param-value> 
        </init-param> 
        <load-on-startup>4</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>dwr-invoker</servlet-name> 
        <url-pattern>/dwr/*</url-pattern> 
    </servlet-mapping> 
 
</web-app> 
dwr.xml
Xml代码 
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd"> 
<dwr> 
    <!-- 对后台类的配置格式确定 --> 
    <allow>        
        <create creator="new" javascript="Chat"> 
            <param name="class" value="com.dwr.chat.Chat" /> 
        </create> 
    </allow> 
</dwr> 

编写好配置文件之后,开始编写页面,我们可以选择html或者jsp都可以
index3.html
Html代码 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
        <title>index3.html</title> 
 
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
        <meta http-equiv="description" content="this is my page"> 
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
        <script type='text/javascript' src='dwr/util.js'></script> 
        <script type='text/javascript' src='dwr/engine.js'></script> 
        <script type='text/javascript' src='dwr/interface/Chat.js'></script> 
        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 
 
    </head> 
 
    <body> 
        <center> 
            <table width="600px" border="1"> 
                <tr> 
                    <td colspan="3" align="center"> 
                        XXXXXX Chat 
                    </td> 
                    <td> 
                        User List 
                    </td> 
                </tr> 
                <tr> 
                    <td colspan="3" style="height: 300px"> 
                        <textarea rows="20" cols="60" readonly id="showmessage" name="showmessage"></textarea> 
                    </td> 
                    <td style="height: 300px"  valign="top"> 
                        <div id="userlist" style="height:310px;overflow : scroll;"></div> 
                    </td> 
                </tr> 
                <tr> 
                    <td colspan="3" align="center"> 
                        <span id="say_name" ></span> 
                        <textarea rows="3" cols="50" id="say_message" name="say_message"></textarea><input type="button" value="say" id="say" onclick="sayMessage()"/> 
                    </td> 
                    <td> 
                        先录入你的昵称<br/> 
                        <input type="text" style="width: 125px" name="name" id="name" /> 
                        <input type="button" value="确定" onclick="register()" /> 
                    </td> 
                </tr> 
            </table> 
        </center> 
    </body> 
    <script type="text/javascript"> 
        dwr.engine.setActiveReverseAjax(true); // 激活反转 重要 
         
        init(); 
         
        function init(){ 
            document.getElementById('say_message').disabled = true; 
            document.getElementById('say').disabled = true; 
        } 
         
        function sayMessage(){ 
            var message_content = DWRUtil.getValue('say_message'); 
            var message_head = document.getElementById('say_name').innerHTML; 
            Chat.sayMessage(message_head+message_content); 
            document.getElementById('say_message').value = ''; 
        } 
         
        function register() { 
            var name = DWRUtil.getValue("name"); 
            Chat.addUser(name,callback); 
        } 
         
        function callback(str) { 
            if(str != ''){ 
                alert(str); 
            }else{ 
                document.getElementById('say_name').innerHTML = DWRUtil.getValue("name") + " 说:"; 
                document.getElementById('say_message').disabled = false; 
                document.getElementById('say').disabled = false; 
            }    
        } 
    </script> 
</html> 
这个页面比较简陋,建议js写在下方,否则firefox会报错

Chat.java
Java代码 
package com.dwr.chat; 
 
import java.util.ArrayList; 
import java.util.Collection; 
 
import javax.servlet.ServletContext; 
import javax.servlet.http.HttpServletRequest; 
 
import org.directwebremoting.ServerContext; 
import org.directwebremoting.ServerContextFactory; 
import org.directwebremoting.proxy.dwr.Util; 
 
public class Chat { 
    static ArrayList<String> name_list = new ArrayList<String>(); 
    static StringBuffer show_message = new StringBuffer();  
 
    public String addUser(String name,HttpServletRequest request) { 
        System.out.println("list.size() = "+name_list.size()); 
        for (String s : name_list) { 
            if (name == null || name.trim().equals(s)) { 
                return "用户名已存在"; 
            }  
        } 
        name_list.add(name.trim()); 
        ServletContext sc = request.getSession().getServletContext(); 
        ServerContext sctx = ServerContextFactory.get(sc); 
        Collection sessions = sctx.getScriptSessionsByPage("/dwr2Demo/index3.html"); 
        Util util = new Util(sessions); 
        show_message.append("\n欢迎"+name+"来到 XXX Chat"); 
        trimMessage(); 
        util.setValue("showmessage", show_message.toString()); 
        printUserList(util); 
        return ""; 
    } 
     
    public void sayMessage(String message,HttpServletRequest request){ 
        ServletContext sc = request.getSession().getServletContext(); 
        ServerContext sctx = ServerContextFactory.get(sc); 
        Collection sessions = sctx.getScriptSessionsByPage("/dwr2Demo/index3.html"); 
        Util util = new Util(sessions); 
        show_message.append("\n"+message); 
        trimMessage(); 
        util.setValue("showmessage", show_message.toString()); 
        printUserList(util); 
    } 
     
    public void trimMessage(){ 
        if(show_message.length() > 2000){ 
            show_message.delete(0, ((show_message.length() - 2000)*2+2)); 
        } 
    } 
     
    public void printUserList(Util util){ 
        StringBuffer userlist = new StringBuffer(); 
        userlist.append("<table>"); 
        for(String s : name_list){ 
            userlist.append("<tr><td><font color='blue'>"+s+"</font></td></tr>"); 
        } 
        userlist.append("</table>"); 
        util.setValue("userlist", userlist.toString()); 
    } 


编写好这个之后,可以运行一下。
        经过测试,发现几个问题  浏览器我现在测试了三种发现三种都有自己的特性
        IE                 :比较正常,有时候会慢一些
        firefox          :每次刷新访问的时候服务器会出现一个异常
        google浏览器:在刷新的时候会无限等待,一直到接收到信息


另一教程:http://hintcnuie.iteye.com/blog/175828

你可能感兴趣的:(DWR)