1. 背景
项目上需要对某个页面的设计功能(低代码)进行最简单的多人协同,有以下需求点:
(1)第一个进入该设计页面的人给编辑权限,后进入的所有人给在线(可申请编辑)权限
(2)在线人员可申请编辑权限,编辑人员可进行【同意/决绝】操作
(3)申请后,除编辑人和申请人,其余人进入不可申请状态
(4)编辑人同意后,编辑人页面自动保存,并退出编辑,与其他人一起进入在线状态;申请人进入编辑状态
(5)整个过程需要在页面中显示在线人员列表
2. 问题
按理说,这是一个很简单的websocket功能,创建配置类、操作类及通信方法实现业务,然后运行测试就行。如果不出意外的话,马上就出意外了。因为是结合的springboot,使用了@ServerEndpoint的方式注入,但因为项目中存在aop,导致出现了启动注册websocket失败的异常(至于为什么有aop就不行,请自行某度)。
3. 解决方案
3.1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
3.2. 创建拦截器
如有必要,在握手前、握手后方法中进行业务逻辑编码。
package cn.xxx.common.filter;
import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import lombok.extern.slf4j.Slf4j;
/**
* WebSocket拦截器
*
* @author xxx
* @date: 2023-07-12 15:27:16
* @Copyright: Copyright (c) 2006 - 2023
* @Company: xxx
* @Version: V1.0
*/
@Component
@Slf4j
public class CustomInterceptor implements HandshakeInterceptor {
/**
* 握手前
*
* @param request
* @param response
* @param wsHandler
* @param attributes
* @return
* @throws Exception
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
return true;
}
/**
* 握手后
*
* @param request
* @param response
* @param wsHandler
* @param exception
*/
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
log.info("握手完成");
}
}
3.3. 创建推送实体类
package cn.xxx.vo.websocket;
import lombok.Getter;
import lombok.Setter;
/**
* 多人协同websocket用户对象
*
* @author xxx
* @date: 2023-07-11 11:29:19
* @Copyright: Copyright (c) 2006 - 2023
* @Company: xxx
* @Version: V1.0
*/
@Getter
@Setter
public class MultiPersonCollaborationVo {
/** 用户id(ip+用户id) */
private String id;
/** 用户状态:1.编辑;2.在线(可申请编辑);3.已申请;4.正在审批;5.不可操作; */
private Integer status;
/** 同意状态:1.同意;2.拒绝 */
private Integer agree;
/** 接收人id */
private String recipientId;
}
3.4. 创建操作类
package cn.xxx.websocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.alibaba.fastjson.JSON;
import cn.xxx.vo.websocket.MultiPersonCollaborationVo;
import lombok.extern.slf4j.Slf4j;
/**
* WebSocket操作类
*
* @author xxx
* @date: 2023-07-12 15:24:20
* @Copyright: Copyright (c) 2006 - 2023
* @Company: xxx
* @Version: V1.0
*/
@Component
@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {
/** 会话 */
private WebSocketSession session;
/** 页面id */
private String pageId;
/** 在线人数 */
public static int onlineNumber = 0;
/** 以页面id为key,WebSocketHandler为对象保存起来 */
private static Map<String, WebSocketHandler> clients = new ConcurrentHashMap<String, WebSocketHandler>();
/** 在线人员列表 */
private List<MultiPersonCollaborationVo> mpcList;
/**
* socket 建立成功事件
*
* @param session
* @throws Exception
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Map<String, Object> paramMap = this.getUriParams(session.getUri().getQuery());
String id = paramMap.get("loginip").toString() + "@" + paramMap.get("id").toString();
onlineNumber++;
log.info("已连接【会话id=" + session.getId() + ",用户id=" + id + "】");
this.session = session;
this.pageId = paramMap.get("pageId").toString();
MultiPersonCollaborationVo mpc = new MultiPersonCollaborationVo();
mpc.setId(id);
// 如果是第一个用户,则设置为编辑者
if (ObjectUtils.isEmpty(this.mpcList)) {
this.mpcList = new ArrayList<>();
mpc.setStatus(1);
} else {
// 后面进来的设置为在线
mpc.setStatus(2);
}
this.mpcList.add(mpc);
try {
clients.put(this.pageId, this);
// 推送结果
Map<String, Object> result = new HashMap<String, Object>();
result.put("status", 200);
result.put("senderId", null);
result.put("msg", null);
result.put("object", this.mpcList);
this.sendMessageTo(JSON.toJSONString(result), this.pageId);
} catch (Exception e) {
this.mpcList.remove(mpc);
log.error("推送用户列表失败:" + e.toString());
}
}
/**
* 接收消息事件
*
* @param session
* @param message
* @throws Exception
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
try {
log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
MultiPersonCollaborationVo param =
JSON.parseObject(message.getPayload().toString(), MultiPersonCollaborationVo.class);
// 找到发送者、接收者
MultiPersonCollaborationVo sender = null;
MultiPersonCollaborationVo recipient = null;
for (MultiPersonCollaborationVo mpc : this.mpcList) {
if (mpc.getId().equals(param.getId())) {
sender = mpc;
continue;
}
if (mpc.getId().equals(param.getRecipientId())) {
recipient = mpc;
continue;
}
if (null != sender && null != recipient) {
break;
}
}
// 推送结果
Map<String, Object> result = new HashMap<String, Object>();
int status = 500;
String senderId = null;
String msg = null;
if (null == sender) {
msg = "发送者为空!";
} else if (null != sender && null == recipient) {
senderId = sender.getId();
msg = "接收者不在线!";
} else if (null != sender && null != recipient && sender.getId().equals(recipient.getId())) {
senderId = sender.getId();
msg = "不能推送消息给自己!";
} else {
// 判断接收状态
// 发送人为编辑人
if (1 == param.getStatus().intValue()) {
// 将所有用户状态设置为在线
for (MultiPersonCollaborationVo mpc : this.mpcList) {
mpc.setStatus(2);
}
// 判断审批是否同意
if (1 == param.getAgree().intValue()) {
// 同意时,设置接收人为编辑
recipient.setStatus(1);
} else if (2 == param.getAgree().intValue()) {
// 拒绝时,设置接收人为申请被拒绝
recipient.setStatus(2);
msg = "您的申请被拒绝了!";
}
senderId = recipient.getId();
} else if (3 == param.getStatus().intValue()) {
// 发送人为申请编辑
// 将所有用户状态设置为不可编辑
for (MultiPersonCollaborationVo mpc : this.mpcList) {
mpc.setStatus(5);
}
// 设置发送人为已申请
sender.setStatus(3);
// 设置接收人为正在审批
recipient.setStatus(4);
senderId = sender.getId();
}
status = 200;
}
result.put("status", status);
result.put("senderId", senderId);
result.put("msg", msg);
result.put("object", this.mpcList);
sendMessageTo(JSON.toJSONString(result), this.pageId);
} catch (Exception e) {
log.info("发生了错误了");
}
}
/**
* socket 断开连接时
*
* @param session
* @param status
* @throws Exception
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
Map<String, Object> paramMap = this.getUriParams(session.getUri().getQuery());
String id = paramMap.get("loginip").toString() + "@" + paramMap.get("id").toString();
onlineNumber--;
if (!ObjectUtils.isEmpty(this.mpcList)) {
Iterator<MultiPersonCollaborationVo> mpcIt = this.mpcList.iterator();
while (mpcIt.hasNext()) {
if (mpcIt.next().getId().equals(id)) {
mpcIt.remove();
}
}
}
try {
// 如果用户列表为空,则删除
if (ObjectUtils.isEmpty(this.mpcList)) {
clients.remove(this.pageId);
log.info(this.pageId + "所有人员已退出");
} else {
// 推送结果
Map<String, Object> result = new HashMap<String, Object>();
result.put("status", 200);
result.put("senderId", null);
result.put("msg", null);
result.put("object", this.mpcList);
sendMessageTo(JSON.toJSONString(result), this.pageId);
log.info("用户【" + id + "】退出,当前在线人数" + onlineNumber);
}
} catch (IOException e) {
log.info("推送在线列表异常:" + e.toString());
}
}
/**
* 获取uri的参数
*
* @author: caip
* @date: 2023-07-12 16:18:26
* @param param
* @return
*/
private Map<String, Object> getUriParams(String param) {
Map<String, Object> result = new HashMap<>();
String[] array = param.split("&");
for (String s : array) {
result.put(s.split("=")[0], s.split("=")[1]);
}
return result;
}
/**
* 推送消息到
*
* @author: caip
* @date: 2023-07-11 10:23:42
* @param message
* @param ToPageId
* @throws IOException
*/
public void sendMessageTo(String message, String toPageId) throws IOException {
for (WebSocketHandler item : clients.values()) {
if (item.pageId.equals(toPageId)) {
item.session.sendMessage(new TextMessage(message));
break;
}
}
}
}
3.5. 创建配置类
package cn.xxx.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import cn.xxx.common.filter.CustomInterceptor;
import cn.xxx.websocket.WebSocketHandler;
import lombok.RequiredArgsConstructor;
/**
* WebSocket配置类
*
* @author xxx
* @date: 2023-07-11 08:51:14
* @Copyright: Copyright (c) 2006 - 2023
* @Company: xxx
* @Version: V1.0
*/
@Configuration
@EnableWebSocket
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer {
private final WebSocketHandler httpAuthHandler;
private final CustomInterceptor customInterceptor;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(httpAuthHandler, "ws").addInterceptors(customInterceptor).setAllowedOrigins("*");
}
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxSessionIdleTimeout(600000L);
return container;
}
}
4. 测试结果