• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

springboot+webscoket通信功能

武飞扬头像
CS_草祭先生
帮助1

1. 背景

        项目上需要对某个页面的设计功能(低代码)进行最简单的多人协同,有以下需求点:

(1)第一个进入该设计页面的人给编辑权限,后进入的所有人给在线(可申请编辑)权限

(2)在线人员可申请编辑权限,编辑人员可进行【同意/决绝】操作

(3)申请后,除编辑人和申请人,其余人进入不可申请状态

(4)编辑人同意后,编辑人页面自动保存,并退出编辑,与其他人一起进入在线状态;申请人进入编辑状态

(5)整个过程需要在页面中显示在线人员列表

2. 问题

        按理说,这是一个很简单的websocket功能,创建配置类、操作类及通信方法实现业务,然后运行测试就行。如果不出意外的话,马上就出意外了。因为是结合的springboot,使用了@ServerEndpoint的方式注入,但因为项目中存在aop,导致出现了启动注册websocket失败的异常(至于为什么有aop就不行,请自行某度)。

3. 解决方案

3.1. 引入依赖

  1.  
    <dependency>
  2.  
    <groupId>org.springframework.boot</groupId>
  3.  
    <artifactId>spring-boot-starter-websocket</artifactId>
  4.  
    </dependency>

3.2. 创建拦截器

如有必要,在握手前、握手后方法中进行业务逻辑编码。

  1.  
    package cn.xxx.common.filter;
  2.  
     
  3.  
    import java.util.Map;
  4.  
     
  5.  
    import org.springframework.http.server.ServerHttpRequest;
  6.  
    import org.springframework.http.server.ServerHttpResponse;
  7.  
    import org.springframework.stereotype.Component;
  8.  
    import org.springframework.web.socket.WebSocketHandler;
  9.  
    import org.springframework.web.socket.server.HandshakeInterceptor;
  10.  
     
  11.  
    import lombok.extern.slf4j.Slf4j;
  12.  
     
  13.  
    /**
  14.  
    * WebSocket拦截器
  15.  
    *
  16.  
    * @author xxx
  17.  
    * @date: 2023-07-12 15:27:16
  18.  
    * @Copyright: Copyright (c) 2006 - 2023
  19.  
    * @Company: xxx
  20.  
    * @Version: V1.0
  21.  
    */
  22.  
    @Component
  23.  
    @Slf4j
  24.  
    public class CustomInterceptor implements HandshakeInterceptor {
  25.  
     
  26.  
    /**
  27.  
    * 握手前
  28.  
    *
  29.  
    * @param request
  30.  
    * @param response
  31.  
    * @param wsHandler
  32.  
    * @param attributes
  33.  
    * @return
  34.  
    * @throws Exception
  35.  
    */
  36.  
    @Override
  37.  
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  38.  
    Map<String, Object> attributes) throws Exception {
  39.  
    return true;
  40.  
    }
  41.  
     
  42.  
    /**
  43.  
    * 握手后
  44.  
    *
  45.  
    * @param request
  46.  
    * @param response
  47.  
    * @param wsHandler
  48.  
    * @param exception
  49.  
    */
  50.  
    @Override
  51.  
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  52.  
    Exception exception) {
  53.  
    log.info("握手完成");
  54.  
    }
  55.  
    }
学新通

3.3. 创建推送实体类

  1.  
    package cn.xxx.vo.websocket;
  2.  
     
  3.  
    import lombok.Getter;
  4.  
    import lombok.Setter;
  5.  
     
  6.  
    /**
  7.  
    * 多人协同websocket用户对象
  8.  
    *
  9.  
    * @author xxx
  10.  
    * @date: 2023-07-11 11:29:19
  11.  
    * @Copyright: Copyright (c) 2006 - 2023
  12.  
    * @Company: xxx
  13.  
    * @Version: V1.0
  14.  
    */
  15.  
    @Getter
  16.  
    @Setter
  17.  
    public class MultiPersonCollaborationVo {
  18.  
    /** 用户id(ip 用户id) */
  19.  
    private String id;
  20.  
    /** 用户状态:1.编辑;2.在线(可申请编辑);3.已申请;4.正在审批;5.不可操作; */
  21.  
    private Integer status;
  22.  
    /** 同意状态:1.同意;2.拒绝 */
  23.  
    private Integer agree;
  24.  
    /** 接收人id */
  25.  
    private String recipientId;
  26.  
    }
学新通

3.4. 创建操作类

  1.  
    package cn.xxx.websocket;
  2.  
     
  3.  
    import java.io.IOException;
  4.  
    import java.util.ArrayList;
  5.  
    import java.util.HashMap;
  6.  
    import java.util.Iterator;
  7.  
    import java.util.List;
  8.  
    import java.util.Map;
  9.  
    import java.util.concurrent.ConcurrentHashMap;
  10.  
     
  11.  
    import org.springframework.stereotype.Component;
  12.  
    import org.springframework.util.ObjectUtils;
  13.  
    import org.springframework.web.socket.CloseStatus;
  14.  
    import org.springframework.web.socket.TextMessage;
  15.  
    import org.springframework.web.socket.WebSocketSession;
  16.  
    import org.springframework.web.socket.handler.TextWebSocketHandler;
  17.  
     
  18.  
    import com.alibaba.fastjson.JSON;
  19.  
     
  20.  
    import cn.xxx.vo.websocket.MultiPersonCollaborationVo;
  21.  
    import lombok.extern.slf4j.Slf4j;
  22.  
     
  23.  
    /**
  24.  
    * WebSocket操作类
  25.  
    *
  26.  
    * @author xxx
  27.  
    * @date: 2023-07-12 15:24:20
  28.  
    * @Copyright: Copyright (c) 2006 - 2023
  29.  
    * @Company: xxx
  30.  
    * @Version: V1.0
  31.  
    */
  32.  
    @Component
  33.  
    @Slf4j
  34.  
    public class WebSocketHandler extends TextWebSocketHandler {
  35.  
    /** 会话 */
  36.  
    private WebSocketSession session;
  37.  
    /** 页面id */
  38.  
    private String pageId;
  39.  
    /** 在线人数 */
  40.  
    public static int onlineNumber = 0;
  41.  
     
  42.  
    /** 以页面id为key,WebSocketHandler为对象保存起来 */
  43.  
    private static Map<String, WebSocketHandler> clients = new ConcurrentHashMap<String, WebSocketHandler>();
  44.  
    /** 在线人员列表 */
  45.  
    private List<MultiPersonCollaborationVo> mpcList;
  46.  
     
  47.  
    /**
  48.  
    * socket 建立成功事件
  49.  
    *
  50.  
    * @param session
  51.  
    * @throws Exception
  52.  
    */
  53.  
    @Override
  54.  
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  55.  
    Map<String, Object> paramMap = this.getUriParams(session.getUri().getQuery());
  56.  
    String id = paramMap.get("loginip").toString() "@" paramMap.get("id").toString();
  57.  
    onlineNumber ;
  58.  
    log.info("已连接【会话id=" session.getId() ",用户id=" id "】");
  59.  
    this.session = session;
  60.  
    this.pageId = paramMap.get("pageId").toString();
  61.  
    MultiPersonCollaborationVo mpc = new MultiPersonCollaborationVo();
  62.  
    mpc.setId(id);
  63.  
    // 如果是第一个用户,则设置为编辑者
  64.  
    if (ObjectUtils.isEmpty(this.mpcList)) {
  65.  
    this.mpcList = new ArrayList<>();
  66.  
    mpc.setStatus(1);
  67.  
    } else {
  68.  
    // 后面进来的设置为在线
  69.  
    mpc.setStatus(2);
  70.  
    }
  71.  
    this.mpcList.add(mpc);
  72.  
     
  73.  
    try {
  74.  
    clients.put(this.pageId, this);
  75.  
    // 推送结果
  76.  
    Map<String, Object> result = new HashMap<String, Object>();
  77.  
    result.put("status", 200);
  78.  
    result.put("senderId", null);
  79.  
    result.put("msg", null);
  80.  
    result.put("object", this.mpcList);
  81.  
    this.sendMessageTo(JSON.toJSONString(result), this.pageId);
  82.  
    } catch (Exception e) {
  83.  
    this.mpcList.remove(mpc);
  84.  
    log.error("推送用户列表失败:" e.toString());
  85.  
    }
  86.  
     
  87.  
    }
  88.  
     
  89.  
    /**
  90.  
    * 接收消息事件
  91.  
    *
  92.  
    * @param session
  93.  
    * @param message
  94.  
    * @throws Exception
  95.  
    */
  96.  
    @Override
  97.  
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
  98.  
    try {
  99.  
    log.info("来自客户端消息:" message "客户端的id是:" session.getId());
  100.  
    MultiPersonCollaborationVo param =
  101.  
    JSON.parseObject(message.getPayload().toString(), MultiPersonCollaborationVo.class);
  102.  
    // 找到发送者、接收者
  103.  
    MultiPersonCollaborationVo sender = null;
  104.  
    MultiPersonCollaborationVo recipient = null;
  105.  
    for (MultiPersonCollaborationVo mpc : this.mpcList) {
  106.  
    if (mpc.getId().equals(param.getId())) {
  107.  
    sender = mpc;
  108.  
    continue;
  109.  
    }
  110.  
    if (mpc.getId().equals(param.getRecipientId())) {
  111.  
    recipient = mpc;
  112.  
    continue;
  113.  
    }
  114.  
    if (null != sender && null != recipient) {
  115.  
    break;
  116.  
    }
  117.  
    }
  118.  
     
  119.  
    // 推送结果
  120.  
    Map<String, Object> result = new HashMap<String, Object>();
  121.  
    int status = 500;
  122.  
    String senderId = null;
  123.  
    String msg = null;
  124.  
    if (null == sender) {
  125.  
    msg = "发送者为空!";
  126.  
    } else if (null != sender && null == recipient) {
  127.  
    senderId = sender.getId();
  128.  
    msg = "接收者不在线!";
  129.  
    } else if (null != sender && null != recipient && sender.getId().equals(recipient.getId())) {
  130.  
    senderId = sender.getId();
  131.  
    msg = "不能推送消息给自己!";
  132.  
    } else {
  133.  
    // 判断接收状态
  134.  
    // 发送人为编辑人
  135.  
    if (1 == param.getStatus().intValue()) {
  136.  
    // 将所有用户状态设置为在线
  137.  
    for (MultiPersonCollaborationVo mpc : this.mpcList) {
  138.  
    mpc.setStatus(2);
  139.  
    }
  140.  
    // 判断审批是否同意
  141.  
    if (1 == param.getAgree().intValue()) {
  142.  
    // 同意时,设置接收人为编辑
  143.  
    recipient.setStatus(1);
  144.  
    } else if (2 == param.getAgree().intValue()) {
  145.  
    // 拒绝时,设置接收人为申请被拒绝
  146.  
    recipient.setStatus(2);
  147.  
    msg = "您的申请被拒绝了!";
  148.  
    }
  149.  
    senderId = recipient.getId();
  150.  
    } else if (3 == param.getStatus().intValue()) {
  151.  
    // 发送人为申请编辑
  152.  
    // 将所有用户状态设置为不可编辑
  153.  
    for (MultiPersonCollaborationVo mpc : this.mpcList) {
  154.  
    mpc.setStatus(5);
  155.  
    }
  156.  
    // 设置发送人为已申请
  157.  
    sender.setStatus(3);
  158.  
    // 设置接收人为正在审批
  159.  
    recipient.setStatus(4);
  160.  
    senderId = sender.getId();
  161.  
    }
  162.  
    status = 200;
  163.  
    }
  164.  
    result.put("status", status);
  165.  
    result.put("senderId", senderId);
  166.  
    result.put("msg", msg);
  167.  
    result.put("object", this.mpcList);
  168.  
    sendMessageTo(JSON.toJSONString(result), this.pageId);
  169.  
    } catch (Exception e) {
  170.  
    log.info("发生了错误了");
  171.  
    }
  172.  
    }
  173.  
     
  174.  
    /**
  175.  
    * socket 断开连接时
  176.  
    *
  177.  
    * @param session
  178.  
    * @param status
  179.  
    * @throws Exception
  180.  
    */
  181.  
    @Override
  182.  
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
  183.  
    Map<String, Object> paramMap = this.getUriParams(session.getUri().getQuery());
  184.  
    String id = paramMap.get("loginip").toString() "@" paramMap.get("id").toString();
  185.  
    onlineNumber--;
  186.  
    if (!ObjectUtils.isEmpty(this.mpcList)) {
  187.  
    Iterator<MultiPersonCollaborationVo> mpcIt = this.mpcList.iterator();
  188.  
    while (mpcIt.hasNext()) {
  189.  
    if (mpcIt.next().getId().equals(id)) {
  190.  
    mpcIt.remove();
  191.  
    }
  192.  
    }
  193.  
    }
  194.  
     
  195.  
    try {
  196.  
    // 如果用户列表为空,则删除
  197.  
    if (ObjectUtils.isEmpty(this.mpcList)) {
  198.  
    clients.remove(this.pageId);
  199.  
    log.info(this.pageId "所有人员已退出");
  200.  
    } else {
  201.  
    // 推送结果
  202.  
    Map<String, Object> result = new HashMap<String, Object>();
  203.  
    result.put("status", 200);
  204.  
    result.put("senderId", null);
  205.  
    result.put("msg", null);
  206.  
    result.put("object", this.mpcList);
  207.  
    sendMessageTo(JSON.toJSONString(result), this.pageId);
  208.  
    log.info("用户【" id "】退出,当前在线人数" onlineNumber);
  209.  
    }
  210.  
    } catch (IOException e) {
  211.  
    log.info("推送在线列表异常:" e.toString());
  212.  
    }
  213.  
    }
  214.  
     
  215.  
    /**
  216.  
    * 获取uri的参数
  217.  
    *
  218.  
    * @author: caip
  219.  
    * @date: 2023-07-12 16:18:26
  220.  
    * @param param
  221.  
    * @return
  222.  
    */
  223.  
    private Map<String, Object> getUriParams(String param) {
  224.  
    Map<String, Object> result = new HashMap<>();
  225.  
    String[] array = param.split("&");
  226.  
    for (String s : array) {
  227.  
    result.put(s.split("=")[0], s.split("=")[1]);
  228.  
    }
  229.  
    return result;
  230.  
    }
  231.  
     
  232.  
    /**
  233.  
    * 推送消息到
  234.  
    *
  235.  
    * @author: caip
  236.  
    * @date: 2023-07-11 10:23:42
  237.  
    * @param message
  238.  
    * @param ToPageId
  239.  
    * @throws IOException
  240.  
    */
  241.  
    public void sendMessageTo(String message, String toPageId) throws IOException {
  242.  
    for (WebSocketHandler item : clients.values()) {
  243.  
    if (item.pageId.equals(toPageId)) {
  244.  
    item.session.sendMessage(new TextMessage(message));
  245.  
    break;
  246.  
    }
  247.  
    }
  248.  
    }
  249.  
    }
学新通

3.5. 创建配置类

  1.  
    package cn.xxx.common.config;
  2.  
     
  3.  
    import org.springframework.context.annotation.Bean;
  4.  
    import org.springframework.context.annotation.Configuration;
  5.  
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
  6.  
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  7.  
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  8.  
    import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
  9.  
     
  10.  
    import cn.xxx.common.filter.CustomInterceptor;
  11.  
    import cn.xxx.websocket.WebSocketHandler;
  12.  
    import lombok.RequiredArgsConstructor;
  13.  
     
  14.  
    /**
  15.  
    * WebSocket配置类
  16.  
    *
  17.  
    * @author xxx
  18.  
    * @date: 2023-07-11 08:51:14
  19.  
    * @Copyright: Copyright (c) 2006 - 2023
  20.  
    * @Company: xxx
  21.  
    * @Version: V1.0
  22.  
    */
  23.  
    @Configuration
  24.  
    @EnableWebSocket
  25.  
    @RequiredArgsConstructor
  26.  
    public class WebSocketConfig implements WebSocketConfigurer {
  27.  
    private final WebSocketHandler httpAuthHandler;
  28.  
    private final CustomInterceptor customInterceptor;
  29.  
     
  30.  
    @Override
  31.  
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  32.  
    registry.addHandler(httpAuthHandler, "ws").addInterceptors(customInterceptor).setAllowedOrigins("*");
  33.  
    }
  34.  
     
  35.  
    @Bean
  36.  
    public ServletServerContainerFactoryBean createWebSocketContainer() {
  37.  
    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
  38.  
    container.setMaxSessionIdleTimeout(600000L);
  39.  
    return container;
  40.  
    }
  41.  
    }
学新通

4. 测试结果

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcccfc
系列文章
更多 icon
同类精品
更多 icon
继续加载