http://www.cnblogs.com/lexus/archive/2011/11/15/2249480.htm
ajax长连接介绍
简单模拟 (jsp + Jquery ajax + struts2)
页面:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Index</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="/js/jquery182.js" ></script>
<script type="text/javascript">
//定时发送消息
var timer = null ;
//当前消息数
var num = 0 ;
//连接数
var connects = 0 ;
$(document).ready(function(){
document.onkeydown = function(e){
if(!e)
e = window.event ;
if(e.keyCode == 13 ){
send() ;
}
};
});
//发送信息
function send(){
var user = $("#user").val() ;
var message = $("#message").val() ;
$(".send_note_div").append("<p>sendmessage" + num + " start...</p>");
$.post("longAjax!save.action",{"user" : user , "num" : num , "message" : message},function(data){
if(data){
var json = data ;
num = json.num ? json.num : 0 ;
}else{
$(".message_div").append("<p>"+ "信息发送错误" + "</p>");
}
});
}
function load(){
//发起连接,连接数加1
connects ++ ;
//始终保持一个连接
if(connects > 1){
connects = 1 ;
return ;
}
var user = $("#user").val() ;
$(".load_note_div").append("<p>loadmessage" + num + " start...</p>");
$.ajax(
{
url:"longAjax!load.action",
type:"POST",
dataType:"json",
data : {"user" : user , "num" : num ,"action" : "list"},
timeout:60000, //超时时间,设置为60s.
success:function(data){
var json = data ;
if(data){
num = json.num ? json.num : 0 ;
$(".load_note_div").append("<p>loadmessage" + num + " end...</p><br/>");
$(".message_div").append(json.returnValue);
//当连接关闭、连接数减1
connects -- ;
//如果连接数少于1 则发起新的连接
if(connects == 0){
load() ;
}
}
},
error : function(){
$(".load_note_div").append("<p>loaderror" + num + " end...</p><br/>");
}
});
}
timer = setInterval(load,20000);
function clear_(){
$(".message_div").text("");
}
</script>
<style type="text/css">
.body_div{
text-align: center;
height: 800px ;
widows: 600px ;
}
.message_div{
height: 300px ;
width: 600px ;
background : #ffa0c1 ;
overflow: auto;
border: 1 px;
text-align: left;
padding-left: 10 px;
}
.load_note_div{
height: 300px ;
width: 200px ;
overflow: auto;
border: 1 px;
text-align: left;
padding-left: 10 px;
}
.send_note_div{
height: 300px ;
width: 200px ;
overflow: auto;
border: 1 px;
text-align: left;
padding-left: 10 px;
}
.send_note_div, .message_div, .load_note_div{
display: inline;
}
</style>
</head>
<body onload="load()">
<div class="body_div">
<div style="display: inline-block;">
<div class="load_note_div"></div>
<div class="message_div">
</div>
<div class="send_note_div"></div>
</div>
<div class="input_div">
<form action="message.jsp" method="post">
<input type="hidden" name="number" id="number" value="" />
<p><span>User:</span> <span> <input type="text" name="user" id = "user" value="" /> </span> </p>
<p><textarea rows="5" cols="60" name="message" id="message" ></textarea></p>
<p><button onclick="send()" >发送</button><button onclick="clear_()" >清空信息</button></p>
</form>
</div>
</div>
</body>
</html>
action :
package action;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LongAjaxConnectAction{
//request 对象
//消息总数量
private static int number = 0;
//消息数组
private static String []messages = new String [10000] ;
private String user ; // 用户
private String message ; // 消息
private Integer num ; // 当前用户已有消息数
private String returnValue ;
public String save() throws Exception{
Date t = new Date() ;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String ms = "<font color=\"blue\">" + user + "</font> : " + message +" " + df.format(t) ;
messages[number ++] = ms ;
return "save" ;
}
public String load() throws Exception{
boolean isWaitting = returnMsg() ;
if(isWaitting){
waitting() ;
}
this.num = number ;
return "load";
}
/**
*判断是否有新消息,并返回新消息,防止同时保存消息与获取消息
**/
public synchronized boolean returnMsg(){
returnValue = null ;
if(num < number){
returnValue = "" ;
for(int i = num ; i< number ; i++){
returnValue += "<p>[" + i +"]" + messages[i] + "</p>" ;
}
return false ;
}
return true ;
}
//保持连接等待新消息 或超时
public void waitting() throws Exception{
Thread t = new Thread(){
long time1 = System.currentTimeMillis() ;
public void run(){
while(true){
if(System.currentTimeMillis() - time1 > 30000){ //连接超时
break ;
}
try{
Thread.sleep(100) ;
}catch(Exception e){
}
if(num < number){ // 有信息
break ;
}
}
}
} ;
t.start() ;
t.join() ; // 保证当线程t执行完后在执行后续任务
returnMsg() ;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getReturnValue() {
return returnValue;
}
public void setReturnValue(String returnValue) {
this.returnValue = returnValue;
}
}