目录
概述:
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocketAPI也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
优点:
较少的控制开销。在连接创建后,服务器和客户端之间交换数据时,用于协议控制的数据包头部相对较小。在不包含扩展的情况下,对于服务器到客户端的内容,此头部大小只有2至10字节(和数据包长度有关);对于客户端到服务器的内容,此头部还需要加上额外的4字节的掩码。相对于HTTP请求每次都要携带完整的头部,此项开销显著减少了。
更强的实时性。由于协议是全双工的,所以服务器可以随时主动给客户端下发数据。相对于HTTP请求需要等待客户端发起请求服务端才能响应,延迟明显更少;即使是和Comet等类似的长轮询比较,其也能在短时间内更多次地传递数据。
保持连接状态。与HTTP不同的是,Websocket需要先创建连接,这就使得其成为一种有状态的协议,之后通信时可以省略部分状态信息。而HTTP请求可能需要在每个请求都携带状态信息(如身份认证等)。
更好的二进制支持。Websocket定义了二进制帧,相对HTTP,可以更轻松地处理二进制内容。
可以支持扩展。Websocket定义了扩展,用户可以扩展协议、实现部分自定义的子协议。如部分浏览器支持压缩等。
更好的压缩效果。相对于HTTP压缩,Websocket在适当的扩展支持下,可以沿用之前内容的上下文,在传递类似的数据时,可以显著地提高压缩率。
握手协议:
WebSocket 是独立的、创建在 TCP 上的协议。
Websocket 通过HTTP/1.1 协议的101状态码进行握手。
为了创建Websocket连接,需要通过浏览器发出请求,之后服务器进行回应,这个过程通常称为“握手”(handshaking)。
1.springboot集成websocket:
1.1新建项目 配置pom.xml:
<dependencies>
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
1.2新建配置类, 开启WebSocket支持:
package com.example.fuwuqi.config;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.util.WebAppRootListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* 开启WebSocket支持
**/
@Configuration
public class WebSocketConfig implements ServletContextInitializer {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
1.3新建WebSocketServer服务端:
@ServerEndpoint("/websocket")
@Component
@Slf4j
public class WebSocket {
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
/**
* 建立连接成功
* @param session
*/
@OnOpen
public void onOpen(Session session){
this.session=session;
webSocketSet.add(this);
log.info("新的连接,总数{}",webSocketSet.size());
}
/**
* 连接关闭
*/
@OnClose
public void onClose(){
this.session=session;
webSocketSet.remove(this);
log.info("连接断开,总数{}",webSocketSet.size());
}
/**
* 接收客户端消息
* @param message
*/
@OnMessage
public void onMessage(String message){
log.info("收到客户端发来的消息:{}",message);
}
/**
* 发送消息
* @param message
*/
public void sendMessage(String message){
log.info("发送消息:{}",message);
for (WebSocket webSocket:webSocketSet){
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.4编写index.html文件来测试通讯:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="text" id="name" /><button onclick="send()">发送消息</button>
</body>
<script>
var websocket = null;
//判断浏览器是否支持websocket
if('WebSocket' in window) {
//实现化WebSocket对象
websocket = new WebSocket("ws://localhost:8080/websocket");
} else {
alert('该浏览器不支持websocket')
}
//打开事件
websocket.onopen = function(event) {
console.log('建立连接');
}
//关闭事件
websocket.onclose = function(event) {
console.log("连接关闭");
}
//获得消息事件
websocket.onmessage = function(event) {
console.log("收到消息:" + event.data);
}
//发生了错误事件
websocket.onerror = function(event) {
console.log("websocket 通信发生错误");
}
window.onbeforeunload = function(event) {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('name').value;
websocket.send(message);
}
</script>
</html>
1.5编写访问接口模仿服务端消息推送场景:
@Controller
public class TestController {
@Resource
private WebSocket webSocket;
/**
* 页面文件入口
*/
@GetMapping("/index")
public String index(){
return "index";
}
/**
* 发送场景模拟
* @param msg
* @return
*/
@GetMapping("/test")
@ResponseBody
public String sendMessage(String msg){
//如果访问的地址中msg参数不为空值,发送msg的值给前端
if(!StringUtils.isEmpty(msg)){
webSocket.sendMessage(msg);
return "服务端发送消息msg:"+msg;
}
return "服务端未发送消息msg:"+msg;
}
}