`
jingliankui123
  • 浏览: 104365 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

jquery-Bayeux数据推送

 
阅读更多

<%@ 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方法

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics