SpringBoot中的WebSocket的理解及使用
使用场景
因为业务需要一个类似客服的功能,这就要求双方能够主动的互相发送信息和接受消息,常用的http请求则在实时性和服务端主动推送这块没法做到实时性,所以综合考虑采用websocket,它是一种全双工的网络技术(具体百度好了,主要以websocket内容使用为主,不干扰大家的重点),能让我们在浏览器和服务端之间通过一次握手形成一条快速通道,直接进行数据的传输
前端+后端 一个demo案例感受下具体的socket运作流程
SpringBoot使用
依赖添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置
SpringBoot 环境得先写个能扫描 @ServerEndpoint 的配置, 不然在客户端连接的时候会一直连不上,ps:不是 SpringBoot 下开发的可跳过
/**
* @Author Gary
* @Date 2022年3月27日 14:35
* @Description: 配置类,让客户端能连接上 springboot下需要
*/
@Configuration
public class SocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
websocket类
package com.mhsb.access.socket;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author: ***
* @Date: 2022/03/23/10:13
* @Description: 定义具体的客户端连接地址,提供socket连接
*/
@Component
@ServerEndpoint(value = "/ws/{userId}")
public class WebSocket {
/**
* 日志记录
*/
private static Logger logger = LoggerFactory.getLogger(WebSocket.class);
/**
* 静态变量,记录当前连接数---线程安全
*/
private static int onlineCount = 0;
/**
* session来对用户发送数据, 获取连接特征userId
*/
private Session session;
private String userId;
/**
* 存放客户端websocket对象
*/
private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void open(@PathParam("userId") String userId, Session session) {
try {
this.userId = userId;
this.session = session;
addCount();
if (webSocketMap