第一步:
1.新建立web项目,将pushlet目录webapps\pushlet\WEB-INF\classes中的pushlet.properties和sources.properties文件拷贝到src目录下
2.将pushlet目录src中的包拷贝到src目录下
3.上一步添加完后,会出现错误,将log4j的包拷贝到项目的lib目录中就可以了
第二步:
1.修改web.xml文件,添加如下代码:
pushlet_userId index.html index.htm index.jsp default.html default.htm default.jsp pushlet nl.justobjects.pushlet.servlet.Pushlet 3 pushlet /pushlet.srv
2.修改ajax-pushlet-client.js文件,在最开始的位置添加 userId:''属性 , _doRequest函数中的var url = PL.pushletURL + '?p_event=' + anEvent;语句,在后面添加如下代码片段:
if (anEvent == 'join' || anEvent == 'join-listen') { url = url + '&userId=' + PL.userId; }
3.修改index.jsp,代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Insert title here
4.修改pushlet源代码,找到nl.justobjects.pushlet.core.SessionManager类,修改代码为如下结构:
/** * Create new Session (but add later). */ public Session createSession(Event anEvent) throws PushletException { // Trivial //return Session.create(createSessionId()); return Session.create(anEvent.getField("userId", "vistor")); }
5.添加Pushlet推送类,代码如下:
package com; import java.util.Random; import javax.servlet.http.HttpServlet; import nl.justobjects.pushlet.core.Event; import nl.justobjects.pushlet.core.EventPullSource; import nl.justobjects.pushlet.core.Session; import nl.justobjects.pushlet.core.SessionManager; public class PushletServ extends HttpServlet { private static final long serialVersionUID = 1L; static public class HwPushlet extends EventPullSource { @Override protected long getSleepTime() { return 5000; } @Override protected Event pullEvent() { Event event = Event.createDataEvent("hwpushlet"); Session[] sessions = SessionManager.getInstance().getSessions(); if (sessions.length > 0) { StringBuilder str = new StringBuilder(""); for (int i = 0; i < sessions.length; i++) { if (!sessions[i].getId().equals("twoseven")) continue; if (!str.toString().equals("")) str.append(","); str.append("'" + sessions[i].getId() + "'"); } if (!str.toString().equals("")) { event.setField("number", ""+(new Random().nextInt(10)));//只向userId为twoseven的用户发送信息 } } return event; } } }
6.修改sources.properties文件为下图所示:
# Define Pull Sources here. These classes must be derived from # nl.justobjects.pushlet.core.EventPullSource # Inner classes are separated with a $ sign from the outer class. source1=com.PushletServ$HwPushlet
7.启动服务器,在浏览器中输入地址,可以看到如下图所示的结果,第一个红线为服务器返回的结果(动态更新),第二个红线是浏览器的请求:
参考资料:
1.Pushlets官网:http://www.pushlets.com/
2.长连接_百度百科:http://baike.baidu.com/view/2831907.htm
3.利用Ajax实现长连接(模拟推送) (1) - liuhh - 博客园:http://www.cnblogs.com/liuhh/archive/2011/05/12/2044230.html
4.使用 Java 实现 Comet 风格的 Web 应用:http://www.ibm.com/developerworks/cn/web/wa-cometjava/
5.Comet:基于 HTTP 长连接的“服务器推”技术:http://www.ibm.com/developerworks/cn/web/wa-lo-comet/index.html
6.浅析Comet技术在Java Web实时系统开发中的应用:http://syue.com/Paper/Computer/App/245823.html
7.Pushlet 推送数据库消息到前台指定用户:http://blog.csdn.net/dataminer_2007/article/details/7653283