一、服务端推送常用技术介绍
简介:服务端常用推送技术介绍,如websocket,sse轮询等
1、客户端轮询:ajax定时拉取(延迟1s)
2、服务端主动推送:WebSocket (时时刷新延迟1毫秒)
全双工的,本质上是一个额外的tcp连接,建立和关闭时握手使用http协议,其他数据传输不使用http协议
更加复杂一些,适用于需要进行复杂双向数据通讯的场景
3、服务端主动推送:SSE (Server Send Event)(时时刷新延迟1毫秒)
html5新标准,用来从服务端实时推送数据到浏览器端,
直接建立在当前http连接上,本质上是保持一个http长连接,轻量协议
简单的服务器数据推送的场景,使用服务器推送事件
学习资料:http://www.w3school.com.cn/html5/html_5_serversentevents.asp
二、SpringBoot2.x服务端主动推送SSE
简介:讲解SpringBoot2.x服务端主动推送Sever-Send-Events
1、localhost:8080/index.html
2、需要把response的类型 改为 text/event-stream,才是sse的类型
1)controller(服务端)
package com.itcast.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/sse")
public class SSEController {
@RequestMapping(value = "/get_data", produces = "text/event-stream;charset=UTF-8")
public String push() {
try {
Thread.sleep(1000);
//第三方数据源调用
} catch (InterruptedException e) {
e.printStackTrace();
}
return "data:xdclass 行情" + Math.random() + "\n\n";
}
}
2)resources/public/下建立html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//需要判断浏览器支不支持EventSource,可以去w3c进行查看
/*
EventSource:服务端推送的对象 (source) ,构造函数传入地址
onmessage:监听器
event:消息
*/
var source = new EventSource('sse/get_data');
source.onmessage = function(event) {
console.info(event.data);
document.getElementById('result').innerText = event.data
};
</script>
</head>
<body>
模拟股票行情
<div>lanpo test</div>
<div id="result"></div>
</body>
</html>
3)