标签:
业务需求:
package com.guoguo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.stringtree.json.JSONReader;
import org.stringtree.json.JSONValidatingReader;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServlet() {
super();
}
/**
* get/post方法的处理函数
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 读取请求报文数据
request.setCharacterEncoding("UTF-8");
// 获取请求的数据
StringBuffer reqData = new StringBuffer();
InputStream in = request.getInputStream();
BufferedInputStream buf = new BufferedInputStream(in);
byte[] buffer = new byte[1024];
int iRead;
while ((iRead = buf.read(buffer)) != -1) {
reqData.append(new String(buffer, 0, iRead, "UTF-8"));
}
// 获取请求的测点名称数组
JSONReader r = new JSONValidatingReader();
@SuppressWarnings("unchecked")
ArrayList<Object> keyList = (ArrayList<Object>) r.read(reqData
.toString());
// 获取订阅主题名称
String aSubject = request.getParameter("subject");
System.out.println("请求的测点:" + reqData.toString() + " , 主题名:" + aSubject);
// 启动一个线程,实现创建Pushlet事件、做业务、向前台推送数据等功能
PushThread pushThread = new PushThread(aSubject, keyList);
pushThread.start();
}
}
package com.guoguo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.stringtree.json.JSONValidatingWriter;
import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.Session;
import nl.justobjects.pushlet.core.SessionManager;
public class PushThread extends Thread {
// 主题
public String aSubject; // 客户端传递过来
// 关键字列表
public ArrayList<Object> keyList; // 客户端传递过来
/**
* 构造函数
*
* @param aSubject
* @param keyList
*/
public PushThread(String aSubject, ArrayList<Object> keyList) {
this.aSubject = aSubject;
this.keyList = keyList;
}
@Override
public void run() {
Event event = Event.createDataEvent(aSubject);
int i = 0;
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// 线程阻塞,结束线程
System.out.println("=========>sleep异常 --->" + "线程"
+ Thread.currentThread().getId() + "关闭");
break;
}
System.out.println("\n-----Thread ID: "
+ Thread.currentThread().getId());
// 判断当前连接的会话个数,没有会话,则线程退出
Session[] sessions = SessionManager.getInstance().getSessions();
// 当前无会话,结束线程
if (0 == sessions.length) {
System.out.println("=========>无sessions --->" + "线程"
+ Thread.currentThread().getId() + "关闭");
break;
}
// 判断当前会话中是否存在订阅该主题的订阅者,不存在则结束线程
boolean if_exist_subscriber = true;
// 遍历所有session
for (int j = 0; j < sessions.length; j++) {
System.out
.println(sessions[j].getSubscriber().match(event) == null ? "Session"
+ j + ": 未订阅该事件 "
: "Session" + j + ":订阅了该事件 ");
if (null != sessions[j].getSubscriber().match(event)) {
if_exist_subscriber = false;
}
}
if (if_exist_subscriber) {
System.out.println("=========>无"+aSubject+"订阅者 --->" + "线程" + Thread.currentThread().getId() + "关闭");
break;
}
// 模拟业务处理:获取各测点的值
HashMap<Object, Object> ret_value = new HashMap<Object, Object>();
for (Object keyStr : keyList) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");// 设置日期格式
String currTm = df.format(new Date());
ret_value.put(keyStr, currTm);
// ret_value.put(keyStr, (10*(new Random().nextFloat())));
}
// 将返回值封装为json数据形式
String ret_string = "[";
ret_string += new JSONValidatingWriter().write(ret_value);
ret_string += "]";
event.setField("key1", ret_string);
// 推送消息
Dispatcher.getInstance().multicast(event); // 向所有和event名称匹配的事件推送
}
}
}
#
# Properties file for EventSource objects to be instantiated.
#
# Place this file in the CLASSPATH (e.g. WEB-INF/classes) or directly under WEB-INF.
#
# $Id: sources.properties,v 1.2 2007/11/10 14:12:16 justb Exp $
#
# Each EventSource is defined as <key>=<classname>
# 1. <key> should be unique within this file but may be any name
# 2. <classname> is the full class name
#
#
# 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=nl.justobjects.pushlet.test.TestEventPullSources$TemperatureEventPullSource
source2=nl.justobjects.pushlet.test.TestEventPullSources$SystemStatusEventPullSource
source3=nl.justobjects.pushlet.test.TestEventPullSources$PushletStatusEventPullSource
source4=nl.justobjects.pushlet.test.TestEventPullSources$AEXStocksEventPullSource
source5=nl.justobjects.pushlet.test.TestEventPullSources$WebPresentationEventPullSource
source6=nl.justobjects.pushlet.test.TestEventPullSources$PingEventPullSource
source7=nl.justobjects.pushlet.test.TestEventPullSources$MyEventPullSource
source8=nl.justobjects.pushlet.test.TestEventPullSources$SpEventPullSource
# TO BE DONE IN NEXT VERSION
# define Push Sources here. These must implement the interface
# nl.justobjects.pushlet.core.EventSource
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<!-- Define the pushlet servlet -->
<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>
<servlet>
<display-name>ChatServlet</display-name>
<servlet-name>ChatServlet</servlet-name>
<servlet-class>com.guoguo.ChatServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ChatServlet</servlet-name>
<url-pattern>/ChatServlet</url-pattern>
</servlet-mapping>
<servlet>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.guoguo.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"
src="<%=basePath%>js/pushlet_js/ajax-pushlet-client.js"></script>
<script type="text/javascript">
var subscriptionId = null;
window.onload = onInit;
window.onbeforeunload = onUnsubscribe;
// 监听后台返回的数据信息,更新页面
function onData(event) {
// 保存订阅编号,用于页面关闭时进行退订
subscriptionId = event.get(‘p_sid‘);
// 更新页面
document.dataEventDisplay.event.value = event.get("key1");
// ------实际案例处理(test)---------
/* var respData = decodeURIComponent(event.get("key1"));
var respObj = eval(respData);
//var respActionNum = respObj.length;
var obj = respObj[0];
var str = "";
for(var p in obj){
if(typeof(obj[p]) != "function"){
str += p + "=" + obj[p] + ", " ;
}
}
alert(str); */
}
// 页面关闭时,取消订阅
function onUnsubscribe() {
if (subscriptionId != null) {
PL.unsubscribe(subscriptionId);
}
}
// 页面加载完,初始化请求、监听
function onInit() {
var aSubject = _getRandomString(6); //主题名
var httpRequest = getXMLHttpRequest();
if (httpRequest) {
var reqData = getData();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
// 请求成功,起pushlet监听
PL._init();
PL.joinListen(aSubject);
} else {
alert("实时请求失败!\n" + httpRequest.statusText);
}
}
}
url = ‘<%=request.getContextPath()%>‘ + ‘/TestServlet‘
+ ‘?subject=‘ + aSubject;
httpRequest.open("POST", url, true);
httpRequest.send(reqData);
}
}
// 请求关键字
function getData() {
var reqData = "[30200000001010, 30200000001012, 30800000003009, 30800000006009]";
return reqData;
}
// 获取http请求
function getXMLHttpRequest() {
req = false;
//本地XMLHttpRequest对象
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch (e) {
req = false;
}
//IE/Windows ActiveX版本
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
return req;
}
// 获取长度为len的随机字符串
function _getRandomString(len) {
var len = len || 32;
var chars = ‘ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz‘;
var maxPos = chars.length;
var pwd = ‘‘;
for (i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
</script>
</head>
<body>
<form name="dataEventDisplay">
<table border="2" bordercolor="white" cellpadding="0" cellspacing="0">
<tr>
<td><textarea cols="60" rows="10" name="event">没有消息 </textarea></td>
</tr>
</table>
</form>
<button onclick="onUnsubscribe()">取消订阅</button>
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/ssslinppp/p/4480889.html