http1.1实现服务器输出持续输出数据
Healthy Mind Lv3

​ 在有些情况下我们需要从服务器不断的推送数据到游览器,而游览器不用发送数据到服务的时候我们可以使用http而不需要 使用websockt

要实现改功能,就需要使用HttpServletResponse 后台需要一个输出流,不断的把数据写入response.getWriter()

中,

1
2
3
4
5
6
7
8
9
10
reader = backupAndRestore.createBackup(backupParam);
String line = null;
StringBuilder sb= new StringBuilder();
while ((line = reader.readLine()) != null){
log.info("ssh log ={}",line);
String lineTab = line + "<br/>";
sb.append(lineTab);
response.getWriter().println(lineTab);
response.getWriter().flush();
}

在游览器里我们可以使用如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

/**
* 使用 底层 XMLHttpRequest 可以实现 response持续加载
* @param url
*/
function loadingDatabaseResult(url){
var xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.seenBytes=0;
$("#loading").show();
xhr.onreadystatechange = function (){
if (xhr.readyState >2){
var newData = xhr.responseText.substr(xhr.seenBytes);
xhr.seenBytes = xhr.responseText.length;
$("#showDetail").append(newData);
var scrollHeight = $("#showDetail").prop('scrollHeight');
$("#backup_detail_modal .modal-body").animate({'scrollTop':scrollHeight},300);
}else if(xhr.readyState == 2 ){
$("#submit").click();
}
if (xhr.readyState == 4){ //销毁 请求对象放置内存益出
$("#loading").hide();
xhr = null;
}
}
xhr.send();
}