一、什么事Http长连接:在网上有很多很多关于Http长连接的文章,但是我看了很多都看不懂。自己总结的所谓的http长连接就是在一请求一个页面后,在服务器端不断开http连接,而是通过response一直在定时的往页面客户端刷新数据。
二、servlet编写
package servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Long currTime = null;
SimpleDateFormat sdf = null;
public void init() throws ServletException {// 初始化一些参数
super.init();
currTime = System.currentTimeMillis();
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 在get中直接调用doPost方法
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {// 长连接方式
boolean flag = true;// 用来表示长连接是否已经被断开(如果数据发送失败了就说明是断开了)
while (true) {
flag = this.sendData("jsFun", sdf.format(currTime), response);
currTime = System.currentTimeMillis();
if (!flag) {// 如果数据发送失败,那么就退出了,说明页面长连接已经断开了
break;
}
try {// 每5秒发送一次
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* @Title: sendData
* @Description: 用来定时向客户端返回数据
* @param jsFun要调用的js函数
* @param data要发送的数据
* @param response
*/
private boolean sendData(String jsFun, String data,
HttpServletResponse response) {
try {
response.setContentType("text/html;charset=utf-8");
/* 这句话比较重要,我们通过response给页面返回一个js脚本,让js执行父页面的对应的jsFun,参数就是我们的data */
response.getWriter().write(
"<script type=\"text/javascript\">parent." + jsFun + "(\""
+ data + "\")</script>");
response.flushBuffer();
return true;
} catch (Exception e) {
System.err.println("long connection was broken!");
return false;
}
}
}
三、页面编写
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"
src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
<title>测试页面</title>
</head>
<body>
<!-- 定义一个form表单, 重要的是target="myiframe",这里把form的请求定向到了myiframe中,然后再myiframe中执行servlet中返回的脚本,调用myiframe的父页面的jsFun,也就是本页面的jsFun -->
<form action="" method="post" id="myForm" target="myiframe"></form>
<!-- iframe要隐藏哦 -->
<iframe id="myiframe" name="myiframe" style="display: none;"></iframe>
<div id="container" style="height: 800px"></div>
</body>
<script type="text/javascript">
function jsFun(data) {//一直被后台调用的方法
$('#container').append("<br/>");
$('#container').append(data);
}
function init() {//用户进入页面后就自动发起form表单的提交,激活长连接
var action = "${pageContext.request.contextPath}/servlet/TestServlet";
$('#myForm').attr("action", action);
$('#myForm').submit();
}
</script>
<script type="text/javascript">
$(function() {
init();
});
</script>
</html>
可以看到数据是每隔5条打印一次的,而且浏览器的页面一直在转圈圈,这就是http长连接的标志。
五、当页面断开连接的时候(刷新页面或关闭页面)
可以看到服务器会自动断开连接,避免资源的浪费。