<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.json-2.2.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.cometd.js"></script>
</head>
<body>
<input type="button" value="hehe" onclick="test()" />
</body>
<script type="text/javascript">
$(function(){
$.comet.init("${pageContext.request.contextPath}/cometd/cometd");
$.comet.subscribe("/test/task", callback);
});
function callback(msg){
alert("eheh进来了");
if(msg&&msg.data&& msg.data.test){
alert(msg.data.test);
}
}
function test(){
alert(new Date().getTime());
$.ajax({
url:"${pageContext.request.contextPath}/CometServlet?time"+new Date().getTime()
});
}
</script>
</html>
$.comet.init("${pageContext.request.contextPath}/cometd/cometd"); //初始化
$.comet.subscribe("/test/task", callback);//订阅名为"/test/task"的主题
这个/test/task与java代码中的
public class DataPushUtil { public static void publish(HttpServletRequest request,String channelName,String context){ if(null!=request){ Bayeux b = (Bayeux)(request.getSession().getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX)); Channel c = b.getChannel(channelName, false); if(null!=c){ Map<String, Object> message = new HashMap<String, Object>(); message.put("test", "jsp: hello world"); c.publish(b.newClient("server_user", null), message, "new server message"); } } } public static void publishTask(HttpServletRequest request,String context){ if(null!=request){ Bayeux b = (Bayeux)(request.getSession().getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX)); Channel c = b.getChannel("/test/task", false); if(null!=c){ Map<String, Object> message = new HashMap<String, Object>(); message.put("test", context); c.publish(b.newClient("server_user", null), message, "new server message"); } } } }
Channel c = b.getChannel("/test/task", false); 当后台调用publishTask方法时,就会调用页面的callback方法
相关推荐
Bayeux是一种通用的、跨平台的、JSON格式的消息协议,设计用于实现服务器推送技术,使得服务器能够主动向客户端发送数据,而不仅仅是响应客户端的请求。这种模式在实时应用,如聊天室、实时股票报价、在线游戏等场景...
atmosphere-bayeux-0.5-sources.jar
atmosphere-bayeux-0.7-sources.jar
atmosphere-bayeux-0.7.2-sources.jar
atmosphere-bayeux-0.7.1-sources.jar
atmosphere-bayeux-0.6.5-sources.jar
atmosphere-bayeux-0.6.4-sources.jar
atmosphere-bayeux-0.6-sources.jar
atmosphere-bayeux-0.6.3-sources.jar
atmosphere-bayeux-0.6.2-sources.jar
atmosphere-bayeux-0.6.1-sources.jar
atmosphere-bayeux-0.7.1.jar
atmosphere-bayeux-0.7.2.jar
atmosphere-bayeux-0.7.jar
atmosphere-bayeux-0.6.4.jar
atmosphere-bayeux-0.6.3.jar
atmosphere-bayeux-0.6.2.jar
atmosphere-bayeux-0.6.1.jar
atmosphere-bayeux-0.6.jar