使用pushlet实现消息服务端推送至客户端

2024-01-25 10:40:32 浏览数 (1)

1、基础概念:Pushlet是一种comet实现:在Servlet机制下,数据从server端的Java对象直接推送(push)到(动态)HTML页面,而无需任何Java applet或者插件的帮助。

2、一个简单的demo:

1)导入所需要的jar包:pushlet.jar

2)将配置文件pushlet.properties、sources.properties导入到src目录下

pushlet.properties:

config.version=1.0.2 controller.class=nl.justobjects.pushlet.core.Controller dispatcher.class=nl.justobjects.pushlet.core.Dispatcher logger.class=nl.justobjects.pushlet.util.Log4jLogger sessionmanager.class=nl.justobjects.pushlet.core.SessionManager session.class=nl.justobjects.pushlet.core.Session subscriber.class=nl.justobjects.pushlet.core.Subscriber subscription.class=nl.justobjects.pushlet.core.Subscription log.level=4 sources.activate=true session.id.generation=randomstring session.timeout.mins=5 queue.size=24 queue.read.timeout.millis=20000 queue.write.timeout.millis=20 listen.force.pull.all=false listen.force.pull.agents=safari pull.refresh.timeout.millis=45000 pull.refresh.wait.min.millis=2000 pull.refresh.wait.max.millis=6000 poll.refresh.timeout.millis=60000 poll.refresh.wait.min.millis=6000 poll.refresh.wait.max.millis=10000

source.properties:

source6=cn.ffcs.pushmessage.plushlet.MessagePlushlet$Plushlet

3)修改web.xml文件如下(url-pattern暂时设置为/pushlet.srv

Xml代码

  1. <servlet-name>pushlet</servlet-name>
  2. <servlet-class>nl.justobjects.pushlet.servlet.Pushlet</servlet-class>
  3. <load-on-startup>1</load-on-startup>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>pushlet</servlet-name>
  7. <url-pattern>/pushlet.srv</url-pattern>
  8. </servlet-mapping>

4)编写一个java类如下

Java代码

代码语言:javascript复制
package cn.ffcs.pushmessage.plushlet;

import java.io.Serializable;

import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.EventPullSource;
import nl.justobjects.pushlet.core.Session;
import nl.justobjects.pushlet.core.SessionManager;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import cn.ffcs.pushmessage.domain.PushMessage;
import cn.ffcs.pushmessage.service.api.IPushMessageService;

@SuppressWarnings("serial")
public class MessagePlushlet implements Serializable, BeanFactoryAware{
	
	private IPushMessageService pushMessageService;
	
	public static class Plushlet extends EventPullSource{
		
		/**
		 * 设置休眠时间
		 */
		@Override
		protected long getSleepTime() {
			return 4000;
		}

		/**
	     * 创建事件
	     * 
	     * 业务部分写在pullEvent()方法中,这个方法会被定时调用。
	     */
		@Override
		protected Event pullEvent() {
			Event event = Event.createDataEvent("/message/plushlet");
			IPushMessageService pushMessageService = (IPushMessageService) getBean("cn.ffcs.pushmessage.service.impl.PushMessageServiceImpl");
			PushMessage pushMessage = pushMessageService.getById(1);
			System.out.println(event.getField("p_id")   "==================");
			System.out.println(event.getField("userId")   "==================");
			System.out.println(event.getField("p_format")   "==================");
			System.out.println(event.getSubject());
			Session[] sessions = SessionManager.getInstance().getSessions(); 
			//sessions[0].getEvent().getField("userId");
			System.out.println(sessions[0].getEvent().getField("userId"));
			event.setField("id", "1");
			return event;
		}
		
	}

	public IPushMessageService getPushMessageService() {
		return pushMessageService;
	}

	public void setPushMessageService(IPushMessageService pushMessageService) {
		this.pushMessageService = pushMessageService;
	}

	private static BeanFactory beanFactory;  
    
    public static Object getBean(String beanName) {  
         return beanFactory.getBean(beanName);  
    }  
      
    public static <T> T getBean(String beanName, Class<T> clazs) {  
         return clazs.cast(getBean(beanName));  
    }  
      
    @SuppressWarnings("static-access")
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {  
    	this.beanFactory = beanFactory;  
    }

	
	
}

还有就是注意Event event = Event.createDataEvent("/message/plushlet");// 事件标识

5)编写jsp文件如下<%@ page language="java" contentType="text/html; charset=UTF-8"

Java代码

代码语言:text复制
    <script type="text/javascript" src="/scripts/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/ajax-pushlet-client.js"></script>
<script src="/scripts/yanue.pop.js"  type="text/javascript"></script>
<script type="text/javascript" src="/scripts/jquery.jplayer.min.js"></script>
<script type="text/javascript"> 

        //对pushlet的初始化,触发web.xml中的servlet。
        PL._init(); 
        //这里的监听的主题,必须在sources.properties中配置的对象中声明这个主题。
        //sources.properties配置着事件源(EventSources),在服务器启动时会自动激活。
        //可以通过服务器的启动记录查看得到。可以将这个文件放到WEB-INF目录下面或者classess目录下面都可以。
        //PL.parameters.push({"userId":"1", "value":"4214f0c0da6760a9e95e3c164998ac06"});  
        PL.joinListen('/message/plushlet'); 
        function onData(event) {
        //alert('123'); 
        //event.setField("userId","123");
        var pop=new Pop("这里是标题,哈哈",
        "http://www.yanue.info/js/pop/pop.html",
        "请输入你的内容简介,这里是内容简介.请输入你的内容简介,这里是内容简介.请输入你的内容简介,这里是内容简介");
            
            getRingData();
        } 
        //onData();
        
         function getRingData(){
        //alert('123');
   var attachmentUrl = "http://localhost:8080/upload/ring/1394107276542.mp3";
   $('#jqDiv div').remove();    //将jplayer渲染的div层移除后重新添加,不然jplayer只会播放一次
$('#jqDiv').append('<div id="jquery_jplayer_1" class="jp-jplayer" style="width:500px;"></div>');
$("#jquery_jplayer_1").jPlayer("stop");
$("#jquery_jplayer_1").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
mp3:attachmentUrl
}).jPlayer("play");
},
swfPath: "js",
supplied: "m4a, oga, mkv, mp3, mp4",
wmode: "window"
});
}
        
</script>
<div id="jqDiv">
<div id="jquery_jplayer_1" class="jp-jplayer" style="width:500px;"></div>
</div>

  1. PL.joinListen('/message/plushlet');//事件标识 在数据源中引用,注意跟上面的红色部分保持一致。

调用getRingData()为弹窗显示后的声音提醒。

代码语言:javascript复制
<body>
<div id="pop" style="display:none;">
	<style type="text/css">
	*{margin:0;padding:0;}
	#pop{background:#fff;width:260px;border:1px solid #e0e0e0;font-size:12px;position: fixed;right:10px;bottom:10px;}
	#popHead{line-height:32px;background:#f6f0f3;border-bottom:1px solid #e0e0e0;position:relative;font-size:12px;padding:0 0 0 10px;}
	#popHead h2{font-size:14px;color:#666;line-height:32px;height:32px;}
	#popHead #popClose{position:absolute;right:10px;top:1px;}
	#popHead a#popClose:hover{color:#f00;cursor:pointer;}
	#popContent{padding:5px 10px;}
	#popTitle a{line-height:24px;font-size:14px;font-family:'微软雅黑';color:#333;font-weight:bold;text-decoration:none;}
	#popTitle a:hover{color:#f60;}
	#popIntro{text-indent:24px;line-height:160%;margin:5px 0;color:#666;}
	#popMore{text-align:right;border-top:1px dotted #ccc;line-height:24px;margin:8px 0 0 0;}
	#popMore a{color:#f60;}
	#popMore a:hover{color:#f00;}
	</style>
	<div id="popHead">
	<a id="popClose" title="关闭">关闭</a>
	<h2>温馨提示</h2>
	</div>
	<div id="popContent">
	<dl>
		<dt id="popTitle"><a href="http://yanue.info/" target="_blank">这里是参数</a></dt>
		<dd id="popIntro">这里是内容简介</dd>
	</dl>
	<p id="popMore"><a href="http://yanue.info/" target="_blank">查看 »</a></p>
	</div>
</div>
<div id="jquery_jplayer_1"></div>
</body>

6)下面说一下web.xml中<url-pattern>的配置问题,查看ajax-pushlet-client.js源码会发现有下面这段代码_getWebRoot: function() {

Js代码

代码语言:text复制
  /** Return directory of this relative to document URL. */ 
  if (PL.webRoot != null) {  
  return PL.webRoot;  
     }  
  //derive the baseDir value by looking for the script tag that loaded this file 
  var head = document.getElementsByTagName('head')[0];  
  var nodes = head.childNodes;  
  for (var i = 0; i < nodes.length;   i) {  
  var src = nodes.item(i).src;  
  if (src) {  
  var index = src.indexOf("lib/ajax-pushlet-client.js");  
  if (index >= 0) {  
                 PL.webRoot = src.substring(0, index);  
  break;  
             }  
         }  
     }  
  return PL.webRoot;  
 },  

注意var index = src.indexOf("lib/ajax-pushlet-client.js");这句话 这个方法就是取webRoot跟路径的,所以<url-pattern>的设置跟这里有关系,还有就是跟你使用ajax-pushlet-client.js的jsp页面有关系,我上面的jsp页面中src="js/ajax-pushlet-client.js"是这样导入js包的,所以我把ajax-pushlet-client.js中的代码改为 var index = src.indexOf("js/ajax-pushlet-client.js"); 取根路径了。

0 人点赞