java ajax长连接请求服务器数据
Servlet 3.0笔记之异步请求Comet推送长轮询(long polling)篇
- AJAX方式请求长轮询
服务器端可以返回原始的数据,或格式化的JSON、XML、JAVASCRIPT信息,客户端可拥有更多的处理自由。在形式上和传统意义上的AJAX GET方式大致一样,只不过下一次的轮询需要等到上一次的轮询数据返回处理完方可进行。
这里给出客户端的小示范:<!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=UTF-8">
<title>jQuery 1.5 with long poll</title>
</head>
<body>
<div id="tip"></div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
<script type="text/javascript">
$(function (){
function log(resp){
$("#tip").html("<b>" + resp + "</b>");
} log("loading"); // 去除缓存
$.ajaxSetup({ cache: false }); function initGet(){
$.get("getNextTime")
.success(function(resp){
log(resp);
}).error(function(){
log("ERROR!");
}).done(initGet);
} initGet();
});
</script>
</body>
</html>基于jQuery 1.5,事件链,比以往更简洁明了,尤其是在done方法中又一次调用自身,棒极了。
服务器端很简单,每1秒输出一次当前系统时间:/**
* 简单模拟每秒输出一次当前系统时间,精细到毫秒
*
* @author yongboy
* @date 2011-2-11
* @version 1.0
*/
@WebServlet("/getNextTime")
public class GetNextTimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
} response.setContentType("text/plain");
PrintWriter out = response.getWriter(); out.print(DateFormatUtils.format(System.currentTimeMillis(),
"yyyy-MM-dd HH:mm:ss SSS"));
out.flush(); out.close();
}
} - JAVASCRIPT标签轮询(Script tag long polling)
引用的JAVASCRIPT脚本文件是可以跨域的,再加上JSONP,更为强大了。
这里给出一个演示,实现功能类似上面。
客户端清单:<!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=UTF-8">
<title>jQuery 1.5 with JSONP FOR Comet</title>
</head>
<body>
<div id="tip"></div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
<script type="text/javascript">
$(function (){
function log(resp){
$("#tip").html("<b>" resp "</b>");
} log("loading"); function jsonp(){
$.getJSON('http://192.168.0.99:8080/servlet3/getNextTime2?callback=?').success(function(resp){
log("now time : " resp);
}).done(jsonp); // 以下方式也是合法的
/*
$.getJSON('http://192.168.0.99:8080/servlet3/getNextTime2?callback=?',function(date){
log(date);
}).done(jsonp);
*/
} jsonp();
});
</script>
</body>
</html>服务器端清单:
/**
* JSONP形式简单模拟每秒输出一次当前系统时间,精细到毫秒
* @author yongboy
* @date 2011-2-11
* @version 1.0
*/
@WebServlet("/getNextTime2")
public class GetNextTimeServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
} String callback = request.getParameter("callback"); if(StringUtils.isBlank(callback)){
callback = "showResult";
} PrintWriter out = response.getWriter(); StringBuilder resultBuilder = new StringBuilder();
resultBuilder
.append(callback)
.append("('")
.append(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss SSS"))
.append("');"); out.print(resultBuilder);
out.flush(); out.close();
}
}每次请求时,都会在HTML头部生成一个JS网络地址(实现跨域):
http://192.168.0.99:8080/servlet3/getNextTime2?callback=jQuery150832738454006945_1297761629067&_=1297761631777
我们不用指定,jquery会自动生成一个随机的函数名。
请求上面地址服务器端在有新的数据输出时,生成的回调JS函数:jQuery150832738454006945_1297761629067('2011-02-15 17:20:33 921');
从下面截图可以看到这一点。

生成相应内容:
不过,长连接情况下,浏览器认为当前JS文件还没有加载完,会一直显示正在加载中。
<html>
<head>
<title>Comet JSONP %u63A8%u9001%u6D4B%u8BD5</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<meta name="author" content="yongboy@gmail.com"/>
<meta name="keywords" content="servlet3, comet, ajax"/>
<meta name="description" content=""/>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
<script type="text/javascript">
String.prototype.template=function(){
var args=arguments;
return this.replace(/\{(\d )\}/g, function(m, i){
return args[i];
});
}
var html = '<div class="logDiv">'
'<div class="contentDiv">{0}</div>'
'<div class="tipDiv">last date : {1}</div>'
'<div class="clear"> </div>'
'</div>'; function showContent(json) {
$("#showDiv").prepend(html.template(json.content, json.date));
}
function initJsonp(){
$.getJSON('http://192.168.0.99/servlet3/getjsonpnew?callback=?').success(function(json){
if(json.state == 1){
showContent(json);
}else{
initJsonp();
return;
}
}).done(initJsonp)
.error(function(){
alert("error!");
});
}
$(function (){
initJsonp();
});
</script>
</head>
<body style="margin: 0; overflow: hidden">
<div id="showDiv" class="inputStyle">loading ...</div>
</body>
</html>
/**
* JSONP获取最新信息
*
* @author yongboy
* @date 2011-2-17
* @version 1.0
*/
@WebServlet(urlPatterns = "/getjsonpnew", asyncSupported = true)
public class GetNewJsonpBlogPosts extends HttpServlet {
private static final long serialVersionUID = 565698895565656L;
private static final Log log = LogFactory.getLog(GetNewJsonpBlogPosts.class); protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Cache-Control", "private");
response.setHeader("Pragma", "no-cache");
response.setHeader("Connection", "Keep-Alive");
response.setHeader("Proxy-Connection", "Keep-Alive");
response.setContentType("text/javascript;charset=UTF-8");
response.setCharacterEncoding("UTF-8"); String timeoutStr = request.getParameter("timeout"); long timeout; if (StringUtils.isNumeric(timeoutStr)) {
timeout = Long.parseLong(timeoutStr);
} else {
// 设置1分钟
timeout = 1L * 60L * 1000L;
} log.info("new request ...");
final HttpServletResponse finalResponse = response;
final HttpServletRequest finalRequest = request;
final AsyncContext ac = request.startAsync(request, finalResponse);
// 设置成长久链接
ac.setTimeout(timeout);
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
log.info("onComplete Event!");
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
} public void onTimeout(AsyncEvent event) throws IOException {
// 尝试向客户端发送超时方法调用,客户端会再次请求/blogpush,周而复始
log.info("onTimeout Event!"); // 通知客户端再次进行重连
final PrintWriter writer = finalResponse.getWriter(); String outString = finalRequest.getParameter("callback")
+ "({state:0,error:'timeout is now'});";
writer.println(outString);
writer.flush();
writer.close(); NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
} public void onError(AsyncEvent event) throws IOException {
log.info("onError Event!");
NewBlogJsonpListener.ASYNC_AJAX_QUEUE.remove(ac);
} public void onStartAsync(AsyncEvent event) throws IOException {
log.info("onStartAsync Event!");
}
}); NewBlogJsonpListener.ASYNC_AJAX_QUEUE.add(ac);
}
}
/**
* 监听器单独线程推送到客户端
*
* @author yongboy
* @date 2011-2-17
* @version 1.0
*/
@WebListener
public class NewBlogJsonpListener implements ServletContextListener {
private static final Log log = LogFactory.getLog(NewBlogListener.class);
public static final BlockingQueue BLOG_QUEUE = new LinkedBlockingQueue();
public static final Queue ASYNC_AJAX_QUEUE = new ConcurrentLinkedQueue(); public void contextDestroyed(ServletContextEvent arg0) {
log.info("context is destroyed!");
} public void contextInitialized(ServletContextEvent servletContextEvent) {
log.info("context is initialized!");
// 启动一个线程处理线程队列
new Thread(runnable).start();
} private Runnable runnable = new Runnable() {
public void run() {
boolean isDone = true; while (isDone) {
if (!BLOG_QUEUE.isEmpty()) {
try {
log.info("ASYNC_AJAX_QUEUE size : "
+ ASYNC_AJAX_QUEUE.size());
MicBlog blog = BLOG_QUEUE.take(); if (ASYNC_AJAX_QUEUE.isEmpty()) {
continue;
} String targetJSON = buildJsonString(blog); for (AsyncContext context : ASYNC_AJAX_QUEUE) {
if (context == null) {
log.info("the current ASYNC_AJAX_QUEUE is null now !");
continue;
}
log.info(context.toString());
PrintWriter out = context.getResponse().getWriter(); if (out == null) {
log.info("the current ASYNC_AJAX_QUEUE's PrintWriter is null !");
continue;
} out.println(context.getRequest().getParameter(
"callback")
+ "(" + targetJSON + ");");
out.flush(); // 通知,执行完成函数
context.complete();
}
} catch (Exception e) {
e.printStackTrace();
isDone = false;
}
}
}
}
}; private static String buildJsonString(MicBlog blog) {
Map<string, object=""> info = new HashMap<string, object="">();
info.put("state", 1);
info.put("content", blog.getContent());
info.put("date",
DateFormatUtils.format(blog.getPubDate(), "HH:mm:ss SSS")); JSONObject jsonObject = JSONObject.fromObject(info); return jsonObject.toString();
}
}
java ajax长连接请求服务器数据的更多相关文章
- Ajax长连接和SignalR(刷新客户端数据)的区别
ajax实现长连接 <%@ page language="java" import="java.util.*" pageEncoding=" ...
- 本地主机作服务器解决AJAX跨域请求访问数据的方法
近几天学到ajax,想测试一下ajax样例,由于之前在阿里租用的服务器过期了,于是想着让本地主机既做服务器又做客户端,只是简单地测试,应该还行. 于是,下载了xampp,下载网址http://www. ...
- Ajax在jQuery中的应用(加载异步数据、请求服务器数据)
加载异步数据 jQuery中的load()方法 load(url,[data],[callback]) url:被加载的页面地址 [data]:可选项表示发送到服务器的数据,其格式为 key/valu ...
- Comet:基于 HTTP 长连接的“服务器推”技术解析
原文链接:http://www.cnblogs.com/deepleo/p/Comet.html 一.背景介绍 传统web请求,是显式的向服务器发送http Request,拿到Response后显示 ...
- Comet:基于 HTTP 长连接的“服务器推”技术
“服务器推”技术的应用 请访问 Ajax 技术资源中心,这是有关 Ajax 编程模型信息的一站式中心,包括很多文档.教程.论坛.blog.wiki 和新闻.任何 Ajax 的新信息都能在这里找到. c ...
- 转载:Comet:基于 HTTP 长连接的“服务器推”技术
转自:http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ 很多应用譬如监控.即时通信.即时报价系统都需要将后台发生的变化实时传送到客户端而无须客 ...
- [转载] Comet:基于 HTTP 长连接的“服务器推”技术
转载自http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ “服务器推”技术的应用 传统模式的 Web 系统以客户端发出请求.服务器端响应的方式工 ...
- Comet:基于 HTTP 长连接的“服务器推”技术(转载)
“服务器推”技术的应用 传统模式的 Web 系统以客户端发出请求.服务器端响应的方式工作.这种方式并不能满足很多现实应用的需求,譬如: 监控系统:后台硬件热插拔.LED.温度.电压发生变化: 即时通信 ...
- 【转】Comet:基于 HTTP 长连接的“服务器推”技术
原文链接:http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ 很多应用譬如监控.即时通信.即时报价系统都需要将后台发生的变化实时传送到客户端而无 ...
随机推荐
- jQuery 遍历 - eq() 方法
<!DOCTYPE html> <html> <head> <style> div { width:60px; height:60px; margin: ...
- 后缀自动机求字典序第k小的串——p3975
又领悟到了一点新的东西,后缀自动机其实可以分为两个数据结构,一个是后缀树,还有一个是自动机 后缀树用来划分endpos集合,并且维护后缀之间的关系,此时每个结点代表的是一些后缀相同且长度连续的子串 自 ...
- NX二次开发-UFUN重命名工程图UF_DRAW_rename_drawing
NX9+VS2012 #include <uf.h> #include <uf_draw.h> #include <uf_part.h> UF_initialize ...
- NX二次开发-算法篇-找相切面
方法1:通过判断相邻面公共边的光顺性来找相切面 1 #include <uf.h> 2 #include <uf_modl.h> 3 #include <uf_obj.h ...
- Python爬虫-《神雕侠侣》
Python3.5 爬取<神雕侠侣>http://www.kanunu8.com/wuxia/201102/1610.html 武侠迷,所以喜欢爬取武侠小说 #!/usr/bin/pyth ...
- Web介绍
web概念概述 javaWeb: 使用java语言开发基于互联网的项目 软件架构: 1.C/S:Client/Server 客户端/服务器端 2.B/S:Browser/Server 浏览器/服务器端 ...
- 在npm中使用bower包依赖工具
什么是bower Bower是一个客户端技术的软件包管理器,它可用于搜索.安装和卸载如JavaScript.HTML.CSS之类的网络资源.其他一些建立在Bower基础之上的开发工具,如YeoMan和 ...
- 使用<script>标签在HTML网页中插入JavaScript代码
新朋友你在哪里(如何插入JS) 我们来看看如何写入JS代码?你只需一步操作,使用<script>标签在HTML网页中插入JavaScript代码.注意, <script>标签要 ...
- android studio toolbar遮挡住下面控件内容
只需要在该控件布局(content_***.xml)加入: app:layout_behavior="@string/appbar_scrolling_view_behavior" ...
- 使用line-height垂直居中在安卓手机上效果不好
前端实现单行垂直居中用的最多的方法可能就是line-height了吧.该属性在pc端和ios手机上效果都很好,可到了安卓手机,有很大几率发生文字上移的现象 知乎有人分析了导致这一现象的原因,Andro ...