• 基于spingboot的websocket订阅、广播、多人聊天室示例


    概述

    基于spingboot的websocket多人聊天系统。包括订阅,广播、点对点单人聊天,多人聊天室功能。

    详细

    一、运行效果

    简单示例

    image.png

    广播

    image.png

    单人聊天

    image.png

    多人聊天室

    image.png

    二、相关代码

    websocket配置

    1. package com.iamgpj.demowebsocket.config;
    2. import com.iamgpj.demowebsocket.v4.SocketChannelInterceptor;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.messaging.simp.config.ChannelRegistration;
    5. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
    6. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
    7. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
    8. import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
    9. import javax.websocket.server.ServerEndpointConfig;
    10. /**
    11. * @author Ives
    12. * @date 2020/4/20 13:51
    13. */
    14. @Configuration
    15. @EnableWebSocketMessageBroker
    16. public class WebSocketConfig extends ServerEndpointConfig.Configurator implements WebSocketMessageBrokerConfigurer {
    17. /**
    18. * 注册端点,发布或者订阅消息的时候需要连接此端点
    19. * addEndpoint websocket的端点,客户端需要注册这个端点进行链接
    20. * setAllowedOrigins 非必须,*表示允许其他域进行连接,跨域
    21. * withSockJS 允许客户端利用sockjs进行浏览器兼容性处理
    22. * @param registry
    23. */
    24. @Override
    25. public void registerStompEndpoints(StompEndpointRegistry registry) {
    26. registry.addEndpoint("/ws/endpoints-websocket")
    27. //.setAllowedOrigins("*")
    28. .withSockJS();
    29. }
    30. /**
    31. * 配置消息代理
    32. * @param registry
    33. */
    34. @Override
    35. public void configureMessageBroker(MessageBrokerRegistry registry) {
    36. // 设置服务器广播消息的基础路径
    37. registry.enableSimpleBroker("/topic", "/user");
    38. // 设置客户端订阅消息的基础路径
    39. registry.setApplicationDestinationPrefixes("/app");
    40. }
    41. /** 配置频道拦截器,用于聊天室 */
    42. @Override
    43. public void configureClientInboundChannel(ChannelRegistration registration) {
    44. registration.interceptors(new SocketChannelInterceptor());
    45. }
    46. }

    聊天室程序

    1. package com.iamgpj.demowebsocket.v4;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.beans.BeanUtils;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.messaging.simp.SimpMessagingTemplate;
    6. import org.springframework.scheduling.annotation.Scheduled;
    7. import org.springframework.stereotype.Service;
    8. import java.time.LocalDateTime;
    9. import java.util.Collection;
    10. import java.util.HashMap;
    11. import java.util.Map;
    12. /**
    13. * @author Ives
    14. * @date 2020/4/21 11:13
    15. */
    16. @Service
    17. @Slf4j
    18. public class ChatRoomService {
    19. @Autowired
    20. private SimpMessagingTemplate template;
    21. /**
    22. * 模拟数据库中存储的用户
    23. */
    24. public static Map<String, String> userMap = new HashMap<>();
    25. /**
    26. * 保存当前在线用户
    27. * 实际应该存储于redis等可持久化缓存服务器中,做到数据共享
    28. */
    29. public static Map<String, String> onlineUserMap = new HashMap<>();
    30. /** 初始化数据 */
    31. static {
    32. userMap.put("张三", "111111");
    33. userMap.put("李四", "111111");
    34. userMap.put("王五", "111111");
    35. userMap.put("赵六", "111111");
    36. userMap.put("陈七", "111111");
    37. }
    38. /**
    39. * 每两秒给客户端推送当前在线用户
    40. */
    41. @Scheduled(fixedRate = 2000)
    42. public void pushOnlineUser() {
    43. Collection<String> users = onlineUserMap.values();
    44. log.info("【聊天室在线用户】={}", users);
    45. template.convertAndSend("/topic/onlineUser", users);
    46. }
    47. /**
    48. * 推送聊天消息
    49. * @param inMessage 内容
    50. */
    51. public void pushChatRoom(InMessage inMessage) {
    52. OutMessage outMessage = new OutMessage();
    53. BeanUtils.copyProperties(inMessage, outMessage);
    54. outMessage.setPushTime(LocalDateTime.now());
    55. template.convertAndSend("/topic/chatRoom", outMessage);
    56. }
    57. }

    三、代码结构

    image.png

    四、相关说明

    1、项目前段使用bootstrap框架,使用maven引入webjars作为样式文件。

    2、访问路径分别为

        http://localhost:8080/v1/index.html

        http://localhost:8080/v2/index.html

        http://localhost:8080/v3/tom.html

        http://localhost:8080/v3/jerry.html

        http://localhost:8080/v4/index.html

    3、聊天室请分别使用不同浏览器登录测试。登录名可以为,张三、李四、王五、赵六....

  • 相关阅读:
    SAP - 事务码
    计算机毕业设计springboot+vue基本微信小程序的学习资料共享小程序
    高低JDK版本中JNDI注入(上)
    【数据挖掘】数据挖掘、关联分析、分类预测、决策树、聚类、类神经网络与罗吉斯回归
    使用es6语法set对数组去重
    一对一,屏对屏,菊风远程同屏解决方案,助力多行业实现数字化协同
    YOLOV7改进-具有隐式知识学习的Efficient解耦头
    神马自然排名如何提高?
    化学试剂磷脂-聚乙二醇-羟基,DSPE-PEG-OH,DSPE-PEG-Hydroxyl,MW:5000
    Mybatis获取自增主键
  • 原文地址:https://blog.csdn.net/hanjiepo/article/details/132842130