---
title: "Pushlet入门案例"
author: "矢风快乐"
date: "2013-12-04T22:45:33Z"
tags: []
slug: "pushlet"
draft: false
lastmod: "2013-12-04T22:47:44Z"
id: 1985346
url: "https://vectorwind.iteye.com/blog/1985346"
---

1.pushlet是将后台信息主动推送到相应的客户端的消息推送技术。由于时间关系，先将第一个成功的代码案例进行完整上传。

2.环境搭建：新建web项目，将pushlet.jar导入项目；

3.然后是2个属性配置文件：sources.properties，pushlet.properties；

4.配置web.xml:

```
	<servlet>
		<servlet-name>pushlet</servlet-name>
		<servlet-class>nl.justobjects.pushlet.servlet.Pushlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>pushlet</servlet-name>
		<url-pattern>/pushlet.srv</url-pattern>
	</servlet-mapping>
```

 5.写pushlet处理类：

 

```
package org.wd.cp.smis.push;

import java.io.Serializable;

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

public class HelloWorldPlushlet implements Serializable {
	static public class HwPlushlet extends EventPullSource {

		@Override
		protected long getSleepTime() {
			return 1000;
		}

		@Override
		protected Event pullEvent() {
			Event event =Event.createDataEvent("/test/hello");
			event.setField("msg","hello pushlet!");
			return event;
		}
	}

}
```

 

 

6.前端接受数据jsp页面（在webroot目录下引入ajax-pushlet-client.js文件）：

 

```
<!DOCTYPE html>
<html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<% String path = request.getContextPath(); %>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
        <script type="text/javascript" src="ajax-pushlet-client.js"></script> 
        <script type="text/javascript"> 
            PL._init(); 
            PL.joinListen('/test/hello'); 
            function onData(event) {
                alert(event.get("msg"));
           } 
      </script>
   </head> 
   <body> 
   <h1>my first pushlet</h1> 
  </body> 
</html>
```

 最后贴上2个属性配置文件：

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.id.size=10
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
```

 pushlet.properties

```
source1=nl.justobjects.pushlet.test.TestEventPullSources$TemperatureEventPullSource
source2=org.wd.cp.smis.push.HelloWorldPlushlet$HwPlushlet
```

  然后就可以测试成功了。