使用Pushlet来实现服务器端向客户端推送信息

1.   实现方式:

有两种实现方式:

1.         通过配置文件来实现定时的从服务器端向客户端推送信息

2.         通过API主动向另外一端推送信息

以下分别给予介绍。

2.   特别注意

在开始测试之前,有三点非常重要,需要实现讲明,否则程序将会无法正常运行:

2.1.     JSP页面上的设定

JSP页面上必须添加以下代码以确保Pushlet能够正确的获得后台服务的地址:

<base href="<%=request.getContextPath()%>">

2.2.     Pushlet的JS文件的Bug修改

需要修改被引用的JS文件ajax-pushlet-client.js的内容,找到

PL.pushletURL = PL._getWebRoot() + 'pushlet.srv';

将其修改为

PL.pushletURL = 'pushlet.srv';

修改的原因是Pushlet进行地址解析的方法在某些应用中会解析错误,导致请求的路径是nullpushlet.srv?,最终导致无法正确的请求到服务器的信息。

2.3.     中文问题

一般情况下,如果不做特殊处理,中文问题将会导致Pushlet的客户端停止响应,解决办法是,在使用Pushlet的客户端代码发送消息之前,将其进行转码,代码为

encodeURIComponent( msg)

3.   正式开始

以上准备工作完毕,就可以正式的开发测试样例了。

3.1.     定时的从后台向前台push信息

(1)       在eclipse中创建一个动态的web工程

(2)       配置及库文件文件:从http://www.pushlets.com/ 下载最新的pushlet的开发包,将其中的以下文件按照描述进行设定

序号

文件名

源位置

目标位置

备注

1.          

pushlet.jar

{pushlet-2.0.4}\lib

项目类路径

如果使用的是applet的话,还需要将pushletclient.jar设置到项目的类路径中去

2.          

log4j.properties

pushlet.properties

sources.properties

{pushlet-2.0.4}\webapps\pushlet\WEB-INF\classes

项目的src根路径

注意稍后需要修改sources.properties,其他两个文件的内容不需要修改

3.          

ajax-pushlet-client.js

{pushlet-2.0.4}\webapps\pushlet\lib

项目的webroot\lib

需要按照之前的描述修改其中的内容

(3)       修改web.xml,将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>

(4)       创建服务器端代码,特别注意类和内部静态类的名字

package com.guoguo;

import java.io.Serializable;

import java.io.UnsupportedEncodingException;

import sun.rmi.runtime.Log;

import nl.justobjects.pushlet.core.Event;

import nl.justobjects.pushlet.core.EventPullSource;

public class HelloWorldPushlet implements Serializable {

private static final long serialVersionUID = -8940934044114406724L;

public static class HWPushlet extends EventPullSource {

Log log = Log.getLog(HWPushlet.class.getName(),

HWPushlet.class.getName(), true);

@Override

protected long getSleepTime() {

return 1000;//每一秒钟自动执行一次

}

@Override

protected Event pullEvent() {

//注意,一下是设定消息的主题/guoguo/helloworld,号称主题是可以继承的

//但是笔者的测试是失败的,也许方法不对,呵呵

Event event = Event.createDataEvent("/guoguo/helloworld");

String data= "hello,world 郭强 "+System.currentTimeMillis();

try {

data=new String(data.getBytes("UTF-8"),"ISO-8859-1");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

event.setField("hw",data);

return event;

}

}

}

(5)       注册服务器端代码为事件源,在sources.properties文件中,添加以下行

source7=com.guoguo.HelloWorldPushlet$HWPushlet

以上方式适用于有内部类的情况,如果没有内部类的话,使用以下的方式进行注册(这时外部类必须继承父类EventPullSource)

source7=com.guoguo.HelloWorldPushlet

(6)       页面(可以参考页面内注释信息)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Pushlet Test</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<base href="<%=request.getContextPath()%>">

</head>

<body>

<script type="text/javascript" src="lib/ajax-pushlet-client.js"></script>

<div id="guoguo"></div>

<script type="text/javascript">

//初始化pushlet客户端

PL._init();

//设定运行时显示调试信息,不需要时,直接删掉即可

PL.setDebug(true);

//设定监听主题:/guoguo/helloworld,与服务器端的主题完全一致

PL.joinListen('/guoguo/helloworld');

//接收到事件后,显示服务器信息

function onData(event) {

guoguo.innerText=(event.get("hw"));

}

</script>

<p1>Pushlet Test</p1>

</body>

</html>

(7)       启动服务器,即可看到页面上的信息每秒钟一次,进行定时的更新

3.2.     主动控制发送消息

3.2.1.   有刷新的提交信息(服务器端主动发送消息)

(1)       创建一个servlet,并且注册到web.xml中

Servlet代码

package com.guoguo;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import nl.justobjects.pushlet.core.Dispatcher;

import nl.justobjects.pushlet.core.Event;

import nl.justobjects.pushlet.core.SessionManager;

public class ChatServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public ChatServlet() {

super();

}

protected void service(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

// myUnicast();

myMulticast();

// myBroadcast();

request.getRequestDispatcher("chat.jsp").forward(request, response);

}

private void myUnicast() {

Event event = Event.createDataEvent("/guoguo/myevent1");

event.setField("key1", "Unicast msg");

Dispatcher.getInstance().unicast(event, "piero"); // 向ID为piero的用户推送

System.out.println("success....");

}

private void myMulticast() {

Event event = Event.createDataEvent("/guoguo/myevent1");

//Event event = Event.createDataEvent("/guoguo");

event.setField("key1", "Multicast msg");

Dispatcher.getInstance().multicast(event); // 向所有和myevent1名称匹配的事件推送

System.out.println("wa success....");

}

private void myBroadcast() {

Event event = Event.createDataEvent("/guoguo/myevent1"); // 向所有的事件推送,不要求和这儿的myevent1名称匹配

event.setField("key1", "Broadcast msg");

Dispatcher.getInstance().broadcast(event);

System.out.println("asw success....");

}

}

Web.xml

<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>

(2)       页面端代码

发送端

<base href="<%=request.getContextPath()%>">

<form action="<%=request.getContextPath()%>/ChatServlet">

<input type="submit">

</form>

接收端

<base href="<%=request.getContextPath()%>">

<script type="text/javascript" src="lib/ajax-pushlet-client.js"></script>

<div id="guoguo"></div>

<script type="text/javascript">

PL._init();

PL.joinListen('/guoguo/myevent1');

function onData(event) {

guoguo.innerText = (event.get("key1"));

}

</script>

启动服务器,从发送端提交信息,内容会在接收端显示出来

3.2.2.   无刷新的提交信息(从客户端发送消息)

发送端

<base href="<%=request.getContextPath()%>">

<script type="text/javascript" src="lib/ajax-pushlet-client.js"></script>

<script type="text/javascript">

PL._init();

function sendnews(msg) {

p_publish('/guoguo/myevent1', 'key1',encodeURIComponent(msg),’key2’,’msg2’);

}

</script>

<input type="text" name="mymsg">

<input type = "button" value="发消息" onclick="sendnews(mymsg.value)"/>

接收端

<base href="<%=request.getContextPath()%>">

<script type="text/javascript" src="lib/ajax-pushlet-client.js"></script>

<div id="guoguo"></div>

<script type="text/javascript">

PL._init();

PL.joinListen('/guoguo/myevent1');

function onData(event) {

guoguo.innerText = (event.get("key1"));

}

</script>

启动服务器,从发送端提交信息,内容会在接收端显示出来

注意:Pushlet目前仅对IE支持良好,经过笔者的测试,FireFox,Chrome均无法实现无刷新的客户端信息提交。

使用Pushlet将消息从服务器端推送到客户端的更多相关文章

  1. SignalR 聊天室实例详解(服务器端推送版)

    翻译自:http://www.codeproject.com/Articles/562023/Asp-Net-SignalR-Chat-Room  (在这里可以下载到实例的源码) Asp.Net Si ...

  2. ASP.NET SignaiR 实现消息的即时推送,并使用Push.js实现通知

    一.使用背景 1. SignalR是什么? ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指 ...

  3. PHP Web实时消息后台服务器推送技术---GoEasy

    越来越多的项目需要用到实时消息的推送与接收,怎样用php实现最方便呢?我这里推荐大家使用GoEasy, 它是一款第三方推送服务平台,使用它的API可以轻松搞定实时推送! 浏览器兼容性:GoEasy推送 ...

  4. Ruby Web实时消息后台服务器推送技术---GoEasy

    越来越多的项目需要用到实时消息的推送与接收,怎样用Ruby实现最方便呢?我这里推荐大家使用GoEasy, 它是一款第三方推送服务平台,使用它的API可以轻松搞定实时推送! 浏览器兼容性:GoEasy推 ...

  5. 拥抱HTTP2.0时代 - HTTP2.0实现服务器端推送Push功能

    在当今的移动互联开发趋势中,nghttp2是一个很值得大家去关注的一个开源项目. 我们在nghttpx模块中实现了HTTP/2服务器推送功能,并且在我们的nghttp2.org网站中启用了该推送功能. ...

  6. JAVA Web实时消息后台服务器推送技术---GoEasy

    ---恢复内容开始--- 越来越多的项目需要用到实时消息的推送与接收,我这里推荐大家使用GoEasy, 它是一款第三方推送服务平台,使用它的API可以轻松搞定实时推送! 浏览器兼容性:GoEasy推送 ...

  7. PHP开发微信公众号(二)消息接受与推送

    上一篇文章我们知道怎么获取二维码,这样别人就可以扫描二维码来关注我们,但是别人关注后,发送消息,我们怎么进行相关处理? 这里我们就来学习下怎么处理处理这些消息,以及推送消息. 学习之前首先你需要有一个 ...

  8. 09点睛Spring MVC4.1-异步请求处理(包含兼容浏览器的服务器端推送)

    转发地址:https://www.iteye.com/blog/wiselyman-2215852 9.1 异步请求处理 Servlet 3开始支持异步请求处理 Spring MVC 3.2开始支持S ...

  9. SuperSocket主动从服务器端推送数据到客户端

    关键字: 主动推送, 推送数据, 客户端推送, 获取Session, 发送数据, 回话快照 通过Session对象发送数据到客户端   前面已经说过,AppSession 代表了一个逻辑的 socke ...

随机推荐

  1. MFC模态和非模态对话框编程

    MFC中对话框有两种形式,一个是模态对话框(model dialog box),一个是非模态对话框(modeless dialog box). 一.模态对话框(model dialog box) 在程 ...

  2. JedisConnectionException: Unexpected end of stream.

    在实际项目中遇到redis读取时报错. 报错是 [ERROR]  redis.clients.jedis.exceptions.JedisConnectionException: Unexpected ...

  3. Chapter 1 First Sight——29

    I was anxious not to be late for class on my first day. 在我第一天上学的时候我非常焦虑我会上课迟到. One of my new acquain ...

  4. 第三十七节,hashlib加密模块

    在使用hashlib模块时需要先 import hashlib 引入模块 用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA ...

  5. 第十九节,基本数据类型,集合set

    集合set,无序,是不允许重复内容的,也就是不允许重复元素,如果有重复,会自动忽略,可接收可迭代类型 (一般用于需要判断和处理交集时候用到) 集合与字典的区别是,集合没有键只有值,字典是有键的字典是一 ...

  6. differences between null pointer and void pointer.

    These are two different concepts, you cannot compare them. What the difference between the skunk and ...

  7. nuget pack 时不包含依赖包(而不是引用项目的dll,区别于IncludeReferencedProjects)

    Excluding development dependencies when creating packages Some NuGet packages are useful as developm ...

  8. 使用HAXM加速Android虚拟机

    Android虚拟机在支持Intel VT技术的CPU上,可以使用HAXM(Hardware Accelerated Execution Manager)得到硬件加速支持,使得虚拟机运行速度得到极大提 ...

  9. 重启库,提示找不到mysqld

    --ledir=/usr/local/mysql/bin    加上server的 directory https://dev.mysql.com/doc/refman/5.5/en/mysqld-s ...

  10. C# 垃圾回收机制(转)

    摘要:今天我们漫谈C#中的垃圾回收机制,本文将从垃圾回收机制的原理讲起,希望对大家有所帮助. GC的前世与今生 虽然本文是以.NET作为目标来讲述GC,但是GC的概念并非才诞生不久.早在1958年,由 ...