灵魂拷问:什么是 WebSocket?它能解决什么问题?
360百科:https://baike.so.com/doc/6840040-7057314.html
WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信--允许服务器主动发送信息给客户端。在 WebSocket 产生之前,双工通信是通过不停发送HTTP请求,从服务器拉取更新来实现,这导致了效率低下。
WebSocket 工作原理
在实现websocket连线过程中,需要通过浏览器发出websocket连线请求,然后服务器发出回应,这个过程通常称为"握手" 。在 WebSocket API,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。在此WebSocket 协议中,为我们实现即时服务带来了两大好处:
1. Header
互相沟通的Header是很小的-大概只有 2 Bytes
2. Server Push
服务器的推送,服务器不再被动的接收到浏览器的请求之后才返回数据,而是在有新数据时就主动推送给浏览器。
我们创建一个 SpringBoot 工程,实现用户A发送消息给用户B,B能及时收到。B也能给A发送消息。
代码结构:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.study</groupId>
<artifactId>study-websocket</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.18.RELEASE</version>
</dependency>
</dependencies>
</project>
配置文件:application.yml
server:
port: 80
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>SpringBoot 整合 WebSocket</title>
</head>
<body>
<span>对方ID:</span>
<input id="userId" type="text" />
<br><br>
<span>消息内容:</span><br/>
<input id="message" type="text"/>
<br><br>
<button onclick="sendMsg()">发送消息</button>
<button onclick="closeWebSocket()">下线</button>
<br><br>
对方说:
<div id="result" style="color: red"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1/send");
} else {
alert('你的浏览器不支持 WebSocket !')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event) {
//setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//显示消息
function setMessageInnerHTML(innerHTML) {
document.getElementById('result').innerHTML += innerHTML + '<br/>';
}
//发送消息
function sendMsg() {
var userId = document.getElementById('userId').value;
var message = document.getElementById('message').value;
var msg = userId + "," + message;
websocket.send(msg);
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.close();
}
</script>
</html>
配置类 WebSocketConfig:
package com.study.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-06-21 下午 8:35
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
核心类处理类 MyWebSocket:
package com.study.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-06-21 下午 10:19
*/
@ServerEndpoint(value = "/send")
@Component
@Slf4j
public class MyWebSocket {
//在线人数
private static AtomicInteger onlineCount = new AtomicInteger(0);
//在线客户端
private static Map<String, Session> clientsMap = new ConcurrentHashMap<>();
//连接建立成功调用的方法
@OnOpen
public void onOpen(Session session) {
//在线数 +1
onlineCount.incrementAndGet();
clientsMap.put(session.getId(), session);
log.info("有新的客户端连接加入,客户ID={},当前总在线人数为:{}", session.getId(), onlineCount.get());
}
//接收消息,并回传
@OnMessage
public void onMessage(String message, Session session) {
log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
try {
String[] split = message.split(",");
String userId = split[0];
String msg = split[1];
Session toSession = clientsMap.get(userId);
if (toSession != null) {
this.sendMessage(msg, toSession);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error(error.getMessage(), error);
}
/**
* 服务端发送消息给客户端
*/
private void sendMessage(String message, Session toSession) {
try {
log.info("服务端给客户端【" + toSession + "】发送消息:" + message);
toSession.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("服务端给客户端发送消息失败:", e);
}
}
//关闭连接
@OnClose
public void onClose(Session session) {
//在线数 -1
onlineCount.decrementAndGet();
clientsMap.remove(session.getId());
log.info("有客户端连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
}
}
启动类:
package com.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-06-21 下午 8:35
*/
@SpringBootApplication
public class WebSocketApp {
public static void main(String[] args) {
SpringApplication.run(WebSocketApp.class, args);
}
}
启动服务,浏览器输入:http://127.0.0.1/ 分开两个浏览器。
然后输入另外一个客户ID,可以在后台查看:
然后,两个客户端就可以互相通信了。
控制台: