SpringBoot2.x系列教程81--SpringBoot中整合WebSockets

作者:一一哥

一. WebSockets简介

1. 什么是Websockets

WebSocket是HTML5的一种新的网络通信协议,它实现了服务端与客户端的全双工通信,建立在传输层TCP协议之上,即浏览器与服务端需要先建立TCP协议,再发送WebSocket连接建立请求。

2. 为什么要有WebSockets

网络通信已经有了http协议,为什么还需要WebSocket协议?

因为http协议有一个缺陷,通信只能由客户端发起请求,服务器端返回查询结果。

比如说我们想要获取一个实时的新闻信息,在每次更新新闻信息后,我们都需要刷新页面才能获取到最新的信息,只有再次发起客户端请求,服务器端才会返回结果。但是服务器端不能做到推送消息给客户端,当然我们可以使用轮询,查看服务器有没有新的消息,比如 "聊天室" 这样的,但是轮询效率是非常低的,因此WebSocket就这样产生了。

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_spring


3. WebSocket创建连接过程

客户端发送请求信息,服务端接收到这个请求并返回响应信息。

当连接建立后,客户端发送http请求时,通过Upgrade:webSocket Connection:Upgrade 告知服务器需要建立的是WebSocket连接,并且还会传递WebSocket版本号、协议的字版本号、原始地址、主机地址, WebSocket相互通信的Header很小,大概只有2Bytes。

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_spring_02


4. WebSocket的优点

WebSocket的最大优点就是服务器可以主动向客户端推送消息,客户端也可以主动向服务器端发送消息

使用WebSockets可以在服务器与客户端之间建立一个非http的双向连接。这个连接是实时的,也是永久的(除非被关闭)。

当服务器想向客户端发送数据时,可以立即将数据推送到客户端的浏览器中,无需重新建立链接,只要客户端有一个被打开的socket(套接字)并且与服务器建立链接,服务器就可以把数据推送到这个socket上。

5. WebSocket的前端API

5.1 建立连接

WebSocket需要接收一个url参数,然后调用WebSocket对象的构造器来建立与服务器之间的通信链接。

如下代码初始化:

var websocket = new WebSocket('wss://echo.websocket.org');

注:

URL字符串必须以 "ws" 或 "wss"(加密通信)开头。

利用上面的代码,我们的通信连接建立之后,就可以进行客户端与服务器端的双向通信了。可以使用WebSocket对象的send方法对服务器发送数据,但是只能发送文本数据(我们可以使用JSON对象把任何js对象转换成文本数据后再进行发送)。

5.2 发送消息的方法

websocket.send("data");

5.3 接收服务器传过来的数据

通过onmessage事件来接收服务器传过来的数据,如下代码:

websocket.onmessage = function(event) {
var data = event.data;
}

5.4 监听socket的打开事件

通过获取onopen事件来监听socket的打开事件。如下代码:

websocket.onopen = function(event) {
// 开始通信时的处理
}

5.5 监听socket的关闭事件

通过获取onclose事件来监听socket的关闭事件。如下代码:

websocket.onclose = function(event) {
// 通信结束时的处理
}

5.6 关闭socket

通过close方法来关闭socket, 如下代码:

websocket.close();

5.6 WebSocket的状态

可以通过读取readyState的属性值来获取WebSocket对象的状态,readyState属性存在以下几种属性值。

  • CONNECTING(数字值为0),表示正在连接;
  • OPEN(数字值为1),表示已建立连接;
  • CLOSING(数字值为2),表示正在关闭连接;
  • CLOSED(数字值为3),表示已关闭链接。

二. SpringBoot2.x整合WebSockets

1. 创建web项目

我们按照之前的经验,创建一个web程序,并将之改造成Spring Boot项目,具体过程略。

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_服务器_03


2. 添加依赖包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>

3.创建WebSocket配置文件

通过该配置类,开启对WebSockets的支持。

package com.yyg.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@Configuration
public class WebSocketConfig {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}

4. 创建WebSockets的Server端

package com.yyg.boot.websockets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@Component
@ServerEndpoint("/server/{uid}")
@Slf4j
public class WebSocketServer {

/**
* 用来记录当前在线连接数量,应该把它设计成线程安全的。
*/
private static int onlineCount = 0;

/**
* concurrent包是线程安全的Set,用来存放每个客户端对应的WebSocket对象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据.
*/
private Session session;

/**
* 接收客户端消息的uid
*/
private String uid = "";

/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("uid") String uid) {
this.session = session;
this.uid = uid;
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//加入到set中
webSocketMap.put(uid, this);
} else {
//加入set中
webSocketMap.put(uid, this);
//在线数加1
addOnlineCount();
}

log.info("用户连接:" + uid + ",当前在线人数为:" + getOnlineCount());

try {
sendMsg("连接成功");
} catch (IOException e) {
log.error("用户:" + uid + ",网络异常!!!!!!");
}
}

/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//从set中删除
subOnlineCount();
}
log.info("用户退出:" + uid + ",当前在线人数为:" + getOnlineCount());
}

/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户id:" + uid + ",接收到的报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (!StringUtils.isEmpty(message)) {
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUID", this.uid);
String toUID = jsonObject.getString("toUID");
//传送给对应的toUserId用户的WebSocket
if (!StringUtils.isEmpty(toUID) && webSocketMap.containsKey(toUID)) {
webSocketMap.get(toUID).sendMsg(jsonObject.toJSONString());
} else {
//若果不在这个服务器上,可以考虑发送到mysql或者redis
log.error("请求的UserId:" + toUID + "不在该服务器上");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 处理错误
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.uid + ",原因:" + error.getMessage());
error.printStackTrace();
}

/**
* 实现服务器主动推送
*/
private void sendMsg(String msg) throws IOException {
this.session.getBasicRemote().sendText(msg);
}

/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("uid") String uid) throws IOException {
log.info("发送消息到:" + uid + ",发送的报文:" + message);
if (!StringUtils.isEmpty(uid) && webSocketMap.containsKey(uid)) {
webSocketMap.get(uid).sendMsg(message);
} else {
log.error("用户" + uid + ",不在线!");
}
}

private static synchronized int getOnlineCount() {
return onlineCount;
}

private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}

private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}

}

5. 创建Controller接口

package com.yyg.boot.web;

import com.yyg.boot.websockets.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@RestController
public class WebSocketController {

@GetMapping("/page")
public ModelAndView page() {
return new ModelAndView("webSocket");
}

@RequestMapping("/push/{toUID}")
public ResponseEntity<String> pushToClient(String message, @PathVariable String toUID) throws IOException {
WebSocketServer.sendInfo(message, toUID);
return ResponseEntity.ok("Send Success!");
}

}

6. 创建前端页面发送消息

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;

//打开WebSocket
function openSocket() {
if (typeof(WebSocket) === "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口,建立连接.
//等同于socket = new WebSocket("ws://localhost:8080/xxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#uid").val();
var socketUrl = "http://localhost:8080/socket/server/" + $("#uid").val();
//将https与http协议替换为ws协议
socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
console.log(socketUrl);
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function () {
console.log("WebSocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//发现消息进入,开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("WebSocket已关闭");
};
//发生了错误事件
socket.onerror = function () {
console.log("WebSocket发生了错误");
}
}
}

//发送消息
function sendMessage() {
if (typeof(WebSocket) === "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
console.log('{"toUID":"' + $("#toUID").val() + '","Msg":"' + $("#msg").val() + '"}');
socket.send('{"toUID":"' + $("#toUID").val() + '","Msg":"' + $("#msg").val() + '"}');
}
}
</script>
<body>
<p>【uid】:
<div><input id="uid" name="uid" type="text" value="5"></div>
<p>【toUID】:
<div><input id="toUID" name="toUID" type="text" value="10"></div>
<p>【Msg】:
<div><input id="msg" name="msg" type="text" value="hello WebSocket"></div>
<p>【第一步操作:】:
<div><button onclick="openSocket()">开启socket</button></div>
<p>【第二步操作:】:
<div><button onclick="sendMessage()">发送消息</button></div>
</body>

</html>

7. 配置application.yml

server:
port: 8080
servlet:
context-path: /socket
spring:
http:
encoding:
force: true
charset: UTF-8
application:
name: websocket-demo
freemarker:
request-context-attribute: request
prefix: /templates/
suffix: .html
content-type: text/html
enabled: true
cache: false
charset: UTF-8
allow-request-override: false
expose-request-attributes: true
expose-session-attributes: true
expose-spring-macro-helpers: true

8. 创建入口类

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@SpringBootApplication
public class SocketApplication {

public static void main(String[] args){
SpringApplication.run(SocketApplication.class,args);
}

}

9. 完整项目结构

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_服务器_04


10. 启动项目进行测试

我们需要在浏览器中打开另个页面,网址都是:

​​http://localhost:8080/socket/page​

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_spring_05

首先我们在第一个页面中,输入如下参数信息,点击发送消息按钮:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_服务器_06


可以看到Console控制台显示的日志信息。

然后我们去Intellij idea中看看后台打印的日志信息:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_spring_07

然后我们在第二个页面中,输入如下参数信息,点击发送消息按钮:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_服务器_08

然后我们去Intellij idea中看看后台打印的日志信息:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_客户端_09

再然后我们回到第一个页面,可以看到log中展示了如下信息:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_客户端_10


说明接收到了从另一个客户端发来的信息。如果在第一个页面中再次点击发送信息的按钮,同样的在第二个页面中可以收到日志信息:

SpringBoot2.x系列教程81--SpringBoot中整合WebSockets_spring_11


至此,我们就实现了WebSocket通信。