当前位置:   article > 正文

springboot + websocket + stomp + vue 实现单\群聊天室_websocket 聊天室

websocket 聊天室

本文主要是介绍websocket + stomp搭建的简易聊天室的实现,本demo聊天室实现了单、群聊天功能;demo后端服务没有使用其他存储数据来做数据支持,除了内定的好友和其好友列表之外,其他数据只有都是临时的,即服务器关掉和重启就不会存在;主要是一个demo尽可能简单明了的来介绍相关功能即可。有什么问题可以在留言哦!并在文章末尾附上demo源码下载!

一、概念介绍

WebSocket:是一种在Web应用程序中实现实时双向通信的协议。与传统的基于HTTP的请求-响应模型不同,WebSocket允许服务器主动向客户端发送消息,而不需要客户端发起请求。客户端通过发起一个特殊的握手请求来与服务器建立WebSocket连接

TOMP:是一种简单而灵活的文本消息传递协议,用于在客户端和服务器之间进行实时通信。它基于帧(frame)的概念,用于在不同的消息中传递数据。建立在底层的WebSocket协议之上,用于在客户端和服务器之间进行异步消息传递,支持发布-订阅(pub-sub)和请求-响应(request-response)模式。还可以通过不同的命令(例如CONNECT、SEND、SUBSCRIBE、UNSUBSCRIBE、DISCONNECT等)和帧头(frame header)来定义不同类型的操作。

 二、项目结构及demo演示

后端采用springboot项目结构;前端采用的vue框架搭建(后面附源码地址或文件)

演示视频

演示视频

三、后端核心代码

在创建好了springboot项目之后

1、导入依赖和模拟静态数据构建

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-websocket</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>commons-codec</groupId>
  16. <artifactId>commons-codec</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.alibaba.fastjson2</groupId>
  20. <artifactId>fastjson2</artifactId>
  21. <version>2.0.27</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.projectlombok</groupId>
  25. <artifactId>lombok</artifactId>
  26. </dependency>
  27. </dependencies>

(实际情况是不可能是模拟静态的数据,都是动态生成的,如添加好友、添加群等等) 

  1. package com.jdh.common;
  2. import com.jdh.model.ChatMessage;
  3. import com.jdh.model.User;
  4. import org.apache.commons.codec.digest.DigestUtils;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. /**
  12. * @ClassName: Constant
  13. * @Author: jdh
  14. * @CreateTime: 2022-11-19
  15. * @Description: 该类主要是模拟数据库等存储的相关数据信息;
  16. * 如系统存在多少用户、每个用户存在好友和群列表、每个群用于的用户列表、用户与好友或者群对于的历史聊天信息等等
  17. * 如果是实际情况下,这些数据就不是像下面这样以静态的方法存储的,本demo主要不像纳入第三方功能,减少配置等等
  18. */
  19. @Configuration
  20. public class Constant {
  21. /**
  22. * 系统中所有存储的用户列表
  23. */
  24. public static final HashMap<String, User> allUserDataList = new HashMap<>();
  25. /**
  26. * 存储用户拥有的好友/群列表
  27. */
  28. public static final HashMap<String, List<String>> ownFriendList = new HashMap<>();
  29. /**
  30. * 存储群含有用户列表
  31. */
  32. public static final HashMap<String, List<String>> ownGroupList = new HashMap<>();
  33. /**
  34. * 所有用户列表
  35. */
  36. public static final List<String> allUserList = new ArrayList<>();
  37. /**
  38. * 在线用户列表
  39. */
  40. public static final List<String> onlineUserList = new ArrayList<>();
  41. /**
  42. * 存储当前已经连接上的用户,以连接的session为key
  43. */
  44. public static final HashMap<String, User> connectUserList = new HashMap<>();
  45. /**
  46. * 存储用户拥有的聊天消息(仅服务启动期间有效)
  47. */
  48. public static final HashMap<String, List<ChatMessage>> ownChatMsgList = new HashMap<>();
  49. /**
  50. * 下面主要是模拟初始化一些相关联的列表数据;
  51. * 实际情况这些一个是存在某个专门存储这些数据的中间件或者数据库中;
  52. * 然后他们直接的关联关系是通过各自的操作来完成的,比如添加好友、加群等等
  53. */
  54. @Bean
  55. public static void initChatRoomData() {
  56. allUserDataList.put("A001", new User("A001", "刘一", "1"));
  57. allUserDataList.put("A002", new User("A002", "陈二", "1"));
  58. allUserDataList.put("A003", new User("A003", "张三", "1"));
  59. allUserDataList.put("A004", new User("A004", "李四", "1"));
  60. allUserDataList.put("A005", new User("A005", "王五", "1"));
  61. allUserDataList.put("A006", new User("A006", "赵六", "1"));
  62. allUserDataList.put("A007", new User("A007", "孙七", "1"));
  63. allUserDataList.put("A008", new User("A008", "周八", "1"));
  64. allUserDataList.put("A009", new User("A009", "吴九", "1"));
  65. allUserList.addAll(Arrays.asList("A001", "A002", "A003", "A004", "A005", "A006", "A007", "A008", "A009"));
  66. allUserDataList.put("B001", new User("B001", "交流群1", "2"));
  67. allUserDataList.put("B002", new User("B002", "交流群2", "2"));
  68. allUserDataList.put("B003", new User("B003", "交流群3", "2"));
  69. //下面是对各个用户的好友列表初始化
  70. ownFriendList.put("A003", new ArrayList<>(
  71. Arrays.asList("A001", "A002", "A004", "A005", "A006", "A007", "A008", "A009", "B001", "B002", "B003")));
  72. ownFriendList.put("A004", new ArrayList<>(
  73. Arrays.asList("A001", "A002", "A003", "A005", "A006", "A007", "A008", "A009", "B001", "B002", "B003")));
  74. ownFriendList.put("A005", new ArrayList<>(
  75. Arrays.asList("A001", "A002", "A003", "A004", "A006", "A007", "A008", "A009", "B001", "B002", "B003")));
  76. ownFriendList.put("A001", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A002", "A006")));
  77. ownFriendList.put("A002", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A001")));
  78. ownFriendList.put("A006", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A001")));
  79. ownFriendList.put("A007", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A008", "A009", "B001", "B003")));
  80. ownFriendList.put("A008", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A007", "A009", "B001", "B002")));
  81. ownFriendList.put("A009", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A007", "A008", "B001", "B003")));
  82. //下面是对群成员初始化
  83. ownGroupList.put("B001", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A007", "A008", "A009")));
  84. ownGroupList.put("B002", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A008")));
  85. ownGroupList.put("B003", new ArrayList<>(Arrays.asList("A003", "A004", "A005", "A007", "A009")));
  86. }
  87. /**
  88. * 传入唯一标识的数据,无论在什么组合形式下,获取唯一标识
  89. * @param uuids
  90. * @return
  91. */
  92. public static String getOnlyTag(String ... uuids){
  93. String str = "";
  94. for (String uuid : uuids) {
  95. str += uuid;
  96. }
  97. char[] charArray = str.toCharArray();
  98. Arrays.sort(charArray);
  99. return DigestUtils.md5Hex(String.valueOf(charArray));
  100. }
  101. }

2、配置websocket以及监听器

  1. package com.jdh.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.messaging.simp.config.ChannelRegistration;
  4. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  5. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  6. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  7. import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
  8. /**
  9. * @ClassName: WebsocketConfig
  10. * @Author: jdh
  11. * @CreateTime: 2022-11-17
  12. * @Description: websocket + stomp 的相关配置类
  13. */
  14. @Configuration
  15. @EnableWebSocketMessageBroker //使能STOMP协议来传输基于代理(MessageBroker)的消息;controller就支持@MessageMapping,就像是使用@requestMapping一样。
  16. public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {
  17. /**
  18. * 配置消息代理
  19. * @param config 消息代理注册对象配置
  20. */
  21. @Override
  22. public void configureMessageBroker(MessageBrokerRegistry config) {
  23. // 配置服务端推送消息给客户端的代理路径
  24. config.enableSimpleBroker("/topic", "/own"); // 定义消息代理前缀
  25. // 客户端向服务端发送消息需有/app 前缀
  26. config.setApplicationDestinationPrefixes("/app"); // 定义消息请求前缀
  27. // 指定用户发送(一对一)的前缀 /user 不配置的话,默认是 /user
  28. // config.setUserDestinationPrefix("/user/");
  29. }
  30. /**
  31. * 注册stomp端点
  32. * @param registry stomp端点注册对象
  33. */
  34. @Override
  35. public void registerStompEndpoints(StompEndpointRegistry registry) {
  36. registry.addEndpoint("/chat") // 注册一个 WebSocket 端点 客户端连接地址ws://127.0.0.1:8097/chat
  37. .setAllowedOrigins("*");
  38. // .withSockJS(); // 支持 SockJS
  39. }
  40. /**
  41. * 采用自定义拦截器,获取connect时候传递的参数
  42. * 使用客户端绑定配置,
  43. * @param registration
  44. */
  45. @Override
  46. public void configureClientInboundChannel(ChannelRegistration registration) {
  47. // registration.interceptors(getHeaderParamInterceptor);
  48. }
  49. }
  1. package com.jdh.config;
  2. import com.alibaba.fastjson2.JSONArray;
  3. import com.jdh.common.Constant;
  4. import com.jdh.model.User;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.event.EventListener;
  8. import org.springframework.messaging.simp.SimpMessageSendingOperations;
  9. import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.socket.messaging.*;
  12. import java.util.Map;
  13. /**
  14. * @ClassName: WebSocketEventListener
  15. * @Author: jdh
  16. * @CreateTime: 2022-05-11
  17. * @Description: 对socket的连接和断连事件进行监听,这样我们才能广播用户进来和出去等操作。
  18. */
  19. @Slf4j
  20. @Component
  21. public class WebSocketEventListener {
  22. @Autowired
  23. private SimpMessageSendingOperations simpMessageSendingOperations;
  24. /**
  25. * 有新用户连接上
  26. *
  27. * @param event
  28. */
  29. @EventListener
  30. public void handleWebSocketConnectListener(SessionConnectEvent event) {
  31. // System.out.println("连接-event => " + event);
  32. StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
  33. String sessionId = event.getMessage().getHeaders().get("simpSessionId").toString();
  34. User user = JSONArray.parseArray(
  35. ((Map) event.getMessage().getHeaders().get("nativeHeaders")).get("user").toString(), User.class).get(0);
  36. System.out.println("用户成功连接:" + sessionId + "; 用户:" + user);
  37. //添加到用户连接列表中
  38. Constant.connectUserList.put(sessionId, user);
  39. }
  40. /**
  41. * 有客户端断开连接
  42. *
  43. * @param event
  44. */
  45. @EventListener
  46. public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
  47. // System.out.println("断开-event => " + event);
  48. StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
  49. String sessionId = event.getSessionId();
  50. // 在此处执行连接断开时的逻辑处理
  51. System.out.println("用户断开连接:" + event.getSessionId());
  52. //移除在线集合中的用户数据
  53. Constant.onlineUserList.remove(Constant.connectUserList.get(sessionId).getUuid());
  54. //移除用户连接列表中当前连接
  55. Constant.connectUserList.remove(sessionId);
  56. }
  57. /***
  58. * 订阅消息
  59. * @param event
  60. */
  61. @EventListener
  62. public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
  63. // log.info("handleWebSocketSubscribeListener - 接收到一个订阅主题的消息:{},用户是:{}", event.getMessage(), event.getUser());
  64. }
  65. /***
  66. * 取消订阅消息
  67. * @param event
  68. */
  69. @EventListener
  70. public void handleWebSocketUnSubscribeListener(SessionUnsubscribeEvent event) {
  71. // log.info("handleWebSocketUnSubscribeListener - 接收到一个取消订阅主题的消息:{},用户是:{}", event.getMessage(), event.getUser());
  72. }
  73. }

3、相关的实体类

  1. package com.jdh.model;
  2. import lombok.Data;
  3. /**
  4. * @ClassName: ChatMessage
  5. * @Author: jdh
  6. * @CreateTime: 2022-11-17
  7. * @Description: 用于发送消息时的数据载体
  8. */
  9. @Data
  10. public class ChatMessage {
  11. /**
  12. * 发送者的uuid,或是账号id,或是唯一标识
  13. */
  14. private String senderUuid;
  15. /**
  16. * 发送者名称
  17. */
  18. private String senderName;
  19. /**
  20. * 发送时间
  21. */
  22. private String sendTime;
  23. /**
  24. * 发送消息内容
  25. */
  26. private String sendContent;
  27. /**
  28. * 接受者uuid,选中当前聊天室的用户uuid
  29. */
  30. private String receiverUuid;
  31. /**
  32. * 接受者名称,选中当前聊天室的用户名称
  33. */
  34. private String receiverName;
  35. /**
  36. * 当前消息类型,1-单聊 2-群聊
  37. */
  38. private String msgType;
  39. }
  1. package com.jdh.model;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. /**
  6. * @ClassName: User
  7. * @Author: jdh
  8. * @CreateTime: 2022-11-19
  9. * @Description: 所有用户数据,这里群也认为是一个用户
  10. */
  11. @Data
  12. @NoArgsConstructor
  13. @AllArgsConstructor
  14. public class User {
  15. /**
  16. * 用户uuid
  17. */
  18. private String uuid;
  19. /**
  20. * 用户名称
  21. */
  22. private String name;
  23. /**
  24. * 用户类型 1-个人 2-群
  25. */
  26. private String type;
  27. }
  1. package com.jdh.vo;
  2. import lombok.Data;
  3. /**
  4. * @ClassName: UserRoomDataVo
  5. * @Author: jdh
  6. * @CreateTime: 2022-11-19
  7. * @Description: 当前聊天历史消息
  8. */
  9. @Data
  10. public class UserRoomVo {
  11. /**
  12. * 当前用户
  13. */
  14. private String uuid;
  15. /**
  16. * 当前聊天室,好友聊天为好友的uuid,群聊为群的uuid
  17. */
  18. private String roomId;
  19. /**
  20. * 当前房间类型 1-好友 2-群聊
  21. */
  22. private String type;
  23. }
  24. ======================================================
  25. package com.jdh.vo;
  26. import com.jdh.model.User;
  27. import lombok.Data;
  28. import java.util.List;
  29. /**
  30. * @ClassName: UserRoomDataVo
  31. * @Author: jdh
  32. * @CreateTime: 2022-11-19
  33. * @Description: 返回当前登录的用户信息和对于的好友列表
  34. */
  35. @Data
  36. public class UserRoomDataVo {
  37. private User user;
  38. private List<User> friendList;
  39. }

4、编写控制类

其中包括了websocket的消息接收和消息转发以及常规的http请求控制类;

注意:由于是一个demo,就没有使用service层来实现业务代码了,全部在controller里面实现业务功能的。

  1. package com.jdh.controller;
  2. import com.jdh.common.Constant;
  3. import com.jdh.model.ChatMessage;
  4. import com.jdh.model.User;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.messaging.handler.annotation.Header;
  7. import org.springframework.messaging.handler.annotation.MessageMapping;
  8. import org.springframework.messaging.handler.annotation.Payload;
  9. import org.springframework.messaging.handler.annotation.SendTo;
  10. import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
  11. import org.springframework.messaging.simp.SimpMessagingTemplate;
  12. import org.springframework.messaging.simp.annotation.SubscribeMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import java.util.ArrayList;
  15. import java.util.Date;
  16. import java.util.List;
  17. /**
  18. * @ClassName: ChatController
  19. * @Author: jdh
  20. * @CreateTime: 2022-11-17
  21. * @Description: websocket 接收和转发客户端消息的api接口类
  22. */
  23. @RestController
  24. public class ChatController {
  25. @Autowired
  26. private SimpMessagingTemplate simpMessagingTemplate;
  27. /**
  28. * 本demo的精髓所在,所有的聊天或者群聊都是这个接口中实现的,好友一对一聊天也是通过订阅地址的不同来完成的
  29. * 其实可用用sendToUser来完成,但是为了方便就没有写,ChatRoomController中预留了一个@sendToUser或者convertAndSendToUser的测试接口
  30. * @param chatMessage
  31. * @param user
  32. * @param headerAccessor
  33. * @return
  34. */
  35. @MessageMapping("/user.sendMessage") // 定义消息发送的请求地址
  36. public String userSendMessage(@Payload ChatMessage chatMessage, User user, SimpMessageHeaderAccessor headerAccessor) {
  37. String subUrl = "";
  38. if ("1".equals(chatMessage.getMsgType())) {
  39. String onlyTag = Constant.getOnlyTag(chatMessage.getSenderUuid(), chatMessage.getReceiverUuid());
  40. //如果是单发,就记录发送者的消息,key采用发送者uuid+接收者uuid
  41. List<ChatMessage> messageList = Constant.ownChatMsgList.get(onlyTag);
  42. if (messageList == null) {
  43. messageList = new ArrayList<>();
  44. }
  45. messageList.add(chatMessage);
  46. Constant.ownChatMsgList.put(onlyTag, messageList);
  47. //需要转发的地址,此处是转发给指定好友订阅的路径
  48. subUrl = "/own/" + chatMessage.getReceiverUuid() + "/" + chatMessage.getSenderUuid() + "/messages";
  49. } else {
  50. //如果是群发,就记录为该群对应的消息
  51. List<ChatMessage> messageList = Constant.ownChatMsgList.get(chatMessage.getReceiverUuid());
  52. if (messageList == null) {
  53. messageList = new ArrayList<>();
  54. }
  55. messageList.add(chatMessage);
  56. Constant.ownChatMsgList.put(chatMessage.getReceiverUuid(), messageList);
  57. //需要转发的地址,此处是转发给指定群消息订阅路径
  58. subUrl = "/topic/" + chatMessage.getReceiverUuid() + "/queue/messages";
  59. }
  60. String info = chatMessage.getSenderUuid() + " 发送消息 '" + chatMessage.getSendContent() + "' 给 " + chatMessage.getReceiverUuid();
  61. System.out.println(info + "; 转发路径:" + subUrl);
  62. //因为转发的路径是不同的,所以就没有使用@sendTo或者@sendToUser注解来实现消息转发
  63. simpMessagingTemplate.convertAndSend(subUrl, chatMessage);
  64. return "消息推送成功!";
  65. }
  66. /**
  67. * 用于stompClient.send('/app/chat.sendMessage',header, JSON.stringify(body));测试接口
  68. * 以及消息转发的"/topic/public"的测试接口
  69. *
  70. * @param chatMessage
  71. * @param user
  72. * @return
  73. */
  74. @MessageMapping("/chat.sendMessage") // 定义消息发送的请求地址
  75. @SendTo("/topic/public") // 定义发送消息的目标地址
  76. public ChatMessage sendMessage(@Payload ChatMessage chatMessage, User user, SimpMessageHeaderAccessor headerAccessor) {
  77. System.out.println("系统接收到的消息:" + chatMessage);
  78. // System.out.println(user);
  79. ChatMessage message = new ChatMessage();
  80. message.setSenderUuid(chatMessage.getReceiverUuid());
  81. message.setSenderName(chatMessage.getReceiverName());
  82. message.setSendContent("系统收到'" + chatMessage.getSendContent() + "'的消息");
  83. message.setSendTime(new Date().toString());
  84. message.setReceiverUuid(chatMessage.getSenderUuid());
  85. message.setReceiverName(chatMessage.getReceiverName());
  86. message.setMsgType("1");
  87. System.out.println("系统回复消息:" + message);
  88. return message;
  89. }
  90. /**
  91. *
  92. * @param authorization
  93. * @param user
  94. */
  95. @SubscribeMapping("/ws://localhost:8083/chat")
  96. public void handleWebSocketConnect(@Header("Authorization") String authorization, @Header("user") String user) {
  97. // 访问和使用authorization和user参数
  98. System.out.println("Authorization: " + authorization);
  99. System.out.println("user: " + user);
  100. // 执行其他操作...
  101. }
  102. }
  1. package com.jdh.controller;
  2. import com.jdh.common.Constant;
  3. import com.jdh.model.ChatMessage;
  4. import com.jdh.model.User;
  5. import com.jdh.util.Result;
  6. import com.jdh.vo.UserRoomDataVo;
  7. import com.jdh.vo.UserRoomVo;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.messaging.simp.SimpMessagingTemplate;
  10. import org.springframework.web.bind.annotation.*;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.stream.Collectors;
  15. /**
  16. * @ClassName: ChatController
  17. * @Author: jdh
  18. * @CreateTime: 2022-11-17
  19. * @Description: 一些常规的http请求类
  20. */
  21. @RestController
  22. @RequestMapping("/chatRoom")
  23. public class ChatRoomController {
  24. @Autowired
  25. private SimpMessagingTemplate simpMessagingTemplate;
  26. /**
  27. * 获取当前未被登录的用户信息
  28. * @return
  29. */
  30. @PostMapping("/getAllUserList")
  31. public Result<List<User>> getAllUserList() {
  32. HashMap<String, User> allUserData = Constant.allUserDataList;
  33. List<String> onlineUserList = Constant.onlineUserList;
  34. //查询出当前可用的用户集合,即未登录的账户
  35. List<User> newUserList = allUserData.entrySet().stream()
  36. .filter(entry -> (!onlineUserList.contains(entry.getKey()) && Constant.allUserList.contains(entry.getKey())))
  37. .map(Map.Entry::getValue)
  38. .collect(Collectors.toList());
  39. return Result.success(newUserList);
  40. }
  41. /**
  42. * 获取当前登录的用户信息,包括好友列表
  43. * @param user
  44. * @return
  45. */
  46. @PostMapping("/getUserData")
  47. public Result<UserRoomDataVo> getUserData(@RequestBody User user) {
  48. if (Constant.onlineUserList.contains(user.getUuid())) {
  49. return Result.error("当前账户已在别处登录;请重新获取再选择账户!");
  50. }
  51. User ownUser = Constant.allUserDataList.get(user.getUuid());
  52. List<String> list = Constant.ownFriendList.get(user.getUuid());
  53. //查询出当前用户对应的好友列表
  54. List<User> friendList = Constant.allUserDataList.entrySet().stream()
  55. .filter(entry -> (list.contains(entry.getKey())))
  56. .map(Map.Entry::getValue)
  57. .collect(Collectors.toList());
  58. UserRoomDataVo userRoomDataVo = new UserRoomDataVo();
  59. userRoomDataVo.setUser(ownUser);
  60. userRoomDataVo.setFriendList(friendList);
  61. //当前用户设置为已上线的账户
  62. Constant.onlineUserList.add(user.getUuid());
  63. return Result.success(userRoomDataVo);
  64. }
  65. /**
  66. * 用户点击下线,通过请求告知服务器接口
  67. * @param user
  68. * @return
  69. */
  70. @PostMapping("/offLine")
  71. public Result<UserRoomDataVo> offLine(@RequestBody User user) {
  72. Constant.onlineUserList.remove(user.getUuid());
  73. String name = Constant.allUserDataList.get(user.getUuid()).getName();
  74. return Result.success(name + "下线了");
  75. }
  76. /**
  77. * 当用户选取某个好友\群聊天室的时候,获取当前用户和当前聊天室的历史消息
  78. * @param userRoomVo
  79. * @return
  80. */
  81. @PostMapping("/getUserRoomMsg")
  82. public Result<List<ChatMessage>> getUserRoomMsg(@RequestBody UserRoomVo userRoomVo) {
  83. String onlyTag = "";
  84. if ("1".equals(userRoomVo.getType())) {
  85. onlyTag = Constant.getOnlyTag(userRoomVo.getUuid(), userRoomVo.getRoomId());
  86. } else {
  87. onlyTag = userRoomVo.getRoomId();
  88. }
  89. List<ChatMessage> chatMessages = Constant.ownChatMsgList.get(onlyTag);
  90. return Result.success(chatMessages);
  91. }
  92. /**
  93. * 用户点击刷新的时候清除所有已登录的账户,更改为未登录状态,这个接口只是方便模拟前端登录而已
  94. * @param uuids
  95. * @return
  96. */
  97. @PostMapping("/cleanAllChatRoomData")
  98. public Result<String> cleanAllChatRoomData(String[] uuids) {
  99. // Constant.onlineUserList.retainAll(new ArrayList<>(uuids));
  100. Constant.onlineUserList.clear();
  101. return Result.success();
  102. }
  103. /**
  104. * 测试消息推送接口
  105. * @return
  106. */
  107. @PostMapping("/checkChat")
  108. public String checkChat() {
  109. System.out.println("接口触发checkChat");
  110. ChatMessage chatMessage = new ChatMessage();
  111. chatMessage.setSenderUuid("0000");
  112. chatMessage.setSenderName("system");
  113. chatMessage.setMsgType("1");
  114. chatMessage.setSendContent("接口触发checkChat");
  115. simpMessagingTemplate.convertAndSend("/topic/public", chatMessage);
  116. simpMessagingTemplate.convertAndSend("/own/A003/A004/messages", chatMessage);
  117. // simpMessagingTemplate.convertAndSendToUser("123", "/queue/private", chatMessage);
  118. return "触发完成";
  119. }
  120. }

四、前端核心代码

前端直接将整个页面的代码全部复制的,后面会有源码地址或者文件

  1. <template>
  2. <div>
  3. <page-nav></page-nav>
  4. <el-divider content-position="center">'websocket + stomp' 聊天室 demo</el-divider>
  5. <div class="chatRoomTag">
  6. <div class="userTag">
  7. <!-- 头部操作栏 -->
  8. <div class="headerHandleTag">
  9. <div class="onlineChatTag">
  10. <el-button type="primary" icon="el-icon-switch-button" size="mini" plain @click="userFirstOnlineHandle()" class="onlineChatTag">
  11. {{ this.userFirst.isOnline ? '下线' : '上线' }}</el-button>
  12. </div>
  13. <div class="chatUserTag">
  14. <el-tag type="" size="medium" class="chatUserTag">
  15. <i class="el-icon-chat-dot-square"></i> {{ this.userFirst.chatRoomTitle }}
  16. </el-tag>
  17. </div>
  18. <div class="userNameTag">
  19. <el-tag type="" size="medium" class="userNameTag">
  20. <i class="el-icon-user-solid"></i> {{ this.userFirst.userName }}
  21. </el-tag>
  22. </div>
  23. </div>
  24. <!-- 聊天室主体栏 -->
  25. <div class="bodyHandleTag">
  26. <!-- 好友列表 -->
  27. <div class="friendListTag">
  28. <el-table :data="this.userFirst.friendList" :show-header="false" :stripe="true" height="750" style="width: 100%">
  29. <el-table-column label="好友列表" show-overflow-tooltip width="120">
  30. <template slot-scope="scope">
  31. <i class="el-icon-user"></i>
  32. <el-button type="text" size="mini" @click="userFirstOpenFriendRoomHandle(scope.$index, scope.row)">
  33. {{ scope.row.type == 2 ? '(群)' : '' }}{{ scope.row.name }}</el-button>
  34. </template>
  35. </el-table-column>
  36. </el-table>
  37. </div>
  38. <!-- 聊天消息主体 -->
  39. <div class="chatRoomMsgTag">
  40. <div class="selectLoginUserTag" v-if="!this.userFirst.isOnline">
  41. <el-button plain @click="userFirstSelectUserListHandle()">点击获取可用账户</el-button>
  42. <el-select v-model="userFirst.uuid" placeholder="请选择一个账号..." style="width: 150px;">
  43. <el-option v-for="item in this.userFirst.allUserList" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
  44. </el-select>
  45. <el-button type="primary" icon="el-icon-switch-button" size="medium" plain @click="userFirstOnlineHandle()" class="onlineChatTag">上线</el-button>
  46. </div>
  47. <!-- 消息展示区域 -->
  48. <div ref="chatMsgTag" class="chatMsgTag" v-if="this.userFirst.isOnline">
  49. <ul ref="recMsgRef1" class="recMsgTag">
  50. <li v-for="(item, index) in this.userFirst.chatMsgList" :key="index"
  51. :style="{'text-align': (userFirst.uuid == item.senderUuid) ? 'right' : 'left'}">
  52. <span span v-if="userFirst.uuid !== item.senderUuid" class="pointTag"></span>
  53. <span style="color: rgb(159, 110, 207);font-size: 12px;">{{item.senderName + ' (' + item.sendTime + ')' }}</span>
  54. <span span v-if="userFirst.uuid == item.senderUuid" class="pointTag"></span>
  55. <br/><span style="color: rgb(123, 12, 12);font-family: Arial, Helvetica, sans-serif;">{{ item.sendContent }}</span>
  56. </li>
  57. </ul>
  58. </div>
  59. <!-- 发送消息区域 -->
  60. <div class="sendMsgTag" v-if="this.userFirst.isOnline">
  61. <el-input v-model="userFirst.sendMsg" size="small" @keydown.enter.native="userFirstSendMsgHandle()" placeholder="输入聊天..." style="width: 85%;"></el-input>
  62. <el-button size="small" @click="userFirstSendMsgHandle()">发送</el-button>
  63. </div>
  64. </div>
  65. </div>
  66. </div>
  67. <div class="userTag">
  68. <!-- 头部操作栏 -->
  69. <div class="headerHandleTag">
  70. <div class="onlineChatTag">
  71. <el-button type="primary" icon="el-icon-switch-button" size="mini" plain @click="userSecondOnlineHandle()" class="onlineChatTag">
  72. {{ this.userSecond.isOnline ? '下线' : '上线' }}</el-button>
  73. </div>
  74. <div class="chatUserTag">
  75. <el-tag type="" size="medium" class="chatUserTag">
  76. <i class="el-icon-chat-dot-square"></i> {{ this.userSecond.chatRoomTitle }}
  77. </el-tag>
  78. </div>
  79. <div class="userNameTag">
  80. <el-tag type="" size="medium" class="userNameTag">
  81. <i class="el-icon-user-solid"></i> {{ this.userSecond.userName }}
  82. </el-tag>
  83. </div>
  84. </div>
  85. <!-- 聊天室主体栏 -->
  86. <div class="bodyHandleTag">
  87. <!-- 好友列表 -->
  88. <div class="friendListTag">
  89. <el-table :data="this.userSecond.friendList" :show-header="false" :stripe="true" height="750" style="width: 100%">
  90. <el-table-column label="好友列表" show-overflow-tooltip width="120">
  91. <template slot-scope="scope">
  92. <i class="el-icon-user"></i>
  93. <el-button type="text" size="mini" @click="userSecondOpenFriendRoomHandle(scope.$index, scope.row)">
  94. {{ scope.row.type == 2 ? '(群)' : '' }}{{ scope.row.name }}</el-button>
  95. </template>
  96. </el-table-column>
  97. </el-table>
  98. </div>
  99. <!-- 聊天消息主体 -->
  100. <div class="chatRoomMsgTag">
  101. <div class="selectLoginUserTag" v-if="!this.userSecond.isOnline">
  102. <el-button plain @click="userSecondSelectUserListHandle()">点击获取可用账户</el-button>
  103. <el-select v-model="userSecond.uuid" placeholder="请选择一个账号..." style="width: 150px;">
  104. <el-option v-for="item in this.userSecond.allUserList" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
  105. </el-select>
  106. <el-button type="primary" icon="el-icon-switch-button" size="medium" plain @click="userSecondOnlineHandle()" class="onlineChatTag">上线</el-button>
  107. </div>
  108. <!-- 消息展示区域 -->
  109. <div ref="chatMsgTag" class="chatMsgTag" v-if="this.userSecond.isOnline">
  110. <ul ref="recMsgRef2" class="recMsgTag">
  111. <li v-for="(item, index) in this.userSecond.chatMsgList" :key="index"
  112. :style="{'text-align': (userSecond.uuid == item.senderUuid) ? 'right' : 'left'}">
  113. <span span v-if="userSecond.uuid !== item.senderUuid" class="pointTag"></span>
  114. <span style="color: rgb(159, 110, 207);font-size: 12px;">{{item.senderName + ' (' + item.sendTime + ')' }}</span>
  115. <span span v-if="userSecond.uuid == item.senderUuid" class="pointTag"></span>
  116. <br/><span style="color: rgb(123, 12, 12);font-family: Arial, Helvetica, sans-serif;">{{ item.sendContent }}</span>
  117. </li>
  118. </ul>
  119. </div>
  120. <!-- 发送消息区域 -->
  121. <div class="sendMsgTag" v-if="this.userSecond.isOnline">
  122. <el-input v-model="userSecond.sendMsg" size="small" @keydown.enter.native="userSecondSendMsgHandle()" placeholder="输入聊天..." style="width: 85%;"></el-input>
  123. <el-button size="small" @click="userSecondSendMsgHandle()">发送</el-button>
  124. </div>
  125. </div>
  126. </div>
  127. </div>
  128. <div class="userTag">
  129. <!-- 头部操作栏 -->
  130. <div class="headerHandleTag">
  131. <div class="onlineChatTag">
  132. <el-button type="primary" icon="el-icon-switch-button" size="mini" plain @click="userThirdOnlineHandle()" class="onlineChatTag">
  133. {{ this.userThird.isOnline ? '下线' : '上线' }}</el-button>
  134. </div>
  135. <div class="chatUserTag">
  136. <el-tag type="" size="medium" class="chatUserTag">
  137. <i class="el-icon-chat-dot-square"></i> {{ this.userThird.chatRoomTitle }}
  138. </el-tag>
  139. </div>
  140. <div class="userNameTag">
  141. <el-tag type="" size="medium" class="userNameTag">
  142. <i class="el-icon-user-solid"></i> {{ this.userThird.userName }}
  143. </el-tag>
  144. </div>
  145. </div>
  146. <!-- 聊天室主体栏 -->
  147. <div class="bodyHandleTag">
  148. <!-- 好友列表 -->
  149. <div class="friendListTag">
  150. <el-table :data="this.userThird.friendList" :show-header="false" :stripe="true" height="750" style="width: 100%">
  151. <el-table-column label="好友列表" show-overflow-tooltip width="120">
  152. <template slot-scope="scope">
  153. <i class="el-icon-user"></i>
  154. <el-button type="text" size="mini" @click="userThirdOpenFriendRoomHandle(scope.$index, scope.row)">
  155. {{ scope.row.type == 2 ? '(群)' : '' }}{{ scope.row.name }}</el-button>
  156. </template>
  157. </el-table-column>
  158. </el-table>
  159. </div>
  160. <!-- 聊天消息主体 -->
  161. <div class="chatRoomMsgTag">
  162. <div class="selectLoginUserTag" v-if="!this.userThird.isOnline">
  163. <el-button plain @click="userThirdSelectUserListHandle()">点击获取可用账户</el-button>
  164. <el-select v-model="userThird.uuid" placeholder="请选择一个账号..." style="width: 150px;">
  165. <el-option v-for="item in this.userThird.allUserList" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
  166. </el-select>
  167. <el-button type="primary" icon="el-icon-switch-button" size="medium" plain @click="userThirdOnlineHandle()" class="onlineChatTag">上线</el-button>
  168. </div>
  169. <!-- 消息展示区域 -->
  170. <div ref="chatMsgTag" class="chatMsgTag" v-if="this.userThird.isOnline">
  171. <ul ref="recMsgRef3" class="recMsgTag">
  172. <li v-for="(item, index) in this.userThird.chatMsgList" :key="index"
  173. :style="{'text-align': (userThird.uuid == item.senderUuid) ? 'right' : 'left'}">
  174. <span span v-if="userThird.uuid !== item.senderUuid" class="pointTag"></span>
  175. <span style="color: rgb(159, 110, 207);font-size: 12px;">{{item.senderName + ' (' + item.sendTime + ')' }}</span>
  176. <span span v-if="userThird.uuid == item.senderUuid" class="pointTag"></span>
  177. <br/><span style="color: rgb(123, 12, 12);font-family: Arial, Helvetica, sans-serif;">{{ item.sendContent }}</span>
  178. </li>
  179. </ul>
  180. </div>
  181. <!-- 发送消息区域 -->
  182. <div class="sendMsgTag" v-if="this.userThird.isOnline">
  183. <el-input v-model="userThird.sendMsg" size="small" @keydown.enter.native="userThirdSendMsgHandle()" placeholder="输入聊天..." style="width: 85%;"></el-input>
  184. <el-button size="small" @click="userThirdSendMsgHandle()">发送</el-button>
  185. </div>
  186. </div>
  187. </div>
  188. </div>
  189. </div>
  190. </div>
  191. </template>
  192. <script>
  193. // import { Client, Message } from '@stomp/stompjs';
  194. export default {
  195. name: 'StudyDemoChatRoom',
  196. data() {
  197. return {
  198. urlPrefix: 'http://localhost:8083',
  199. socket: null,
  200. stompClient: null,
  201. subscription: null,
  202. userFirst:{
  203. isOnline: false,
  204. stompClient: null,
  205. subscription: null,
  206. checkSub: null,
  207. chatRoomTitle: '聊天室',//当前正在聊天的聊天室
  208. uuid: '',//当前登录的用户账户
  209. userName: 'admin',//当前登录的用户名
  210. sendMsg: '',//当前输入的聊天消息
  211. allUserList:[],//当前可选的登录账号
  212. openFriend: {},//打开的当前聊天室
  213. friendList: [],//好友列表
  214. chatMsgList: []//当前聊天室的聊天内容
  215. },
  216. userSecond:{
  217. isOnline: false,
  218. stompClient: null,
  219. chatRoomTitle: '聊天室',
  220. uuid: '',
  221. userName: 'admin',
  222. sendMsg: '',
  223. allUserList:[],
  224. openFriend: {},
  225. friendList: [],
  226. chatMsgList: []
  227. },
  228. userThird:{
  229. isOnline: false,
  230. stompClient: null,
  231. chatRoomTitle: '聊天室',
  232. uuid: '',
  233. userName: 'admin',
  234. sendMsg: '',
  235. allUserList:[],
  236. openFriend: {},
  237. friendList: [],
  238. chatMsgList: []
  239. },
  240. openFriend: {
  241. uuid: '',
  242. name: '',
  243. type: ''
  244. },
  245. chatMsg: {
  246. senderUuid: '',//发送者uuid
  247. senderName: '',//发送者姓名
  248. sendTime: '',//发送时间
  249. sendContent: '',//发送内容
  250. receiver: '',//接受者,即当前登录用户uuid
  251. msgType: ''//消息类型,单聊还是群聊
  252. }
  253. };
  254. },
  255. created() {
  256. // this.socket = new WebSocket('ws://localhost:8080/chat');
  257. // this.stompClient = Stomp.client('ws://localhost:8083/chat')
  258. // 添加beforeunload事件监听器
  259. window.addEventListener('load', this.handlePageRefresh);
  260. },
  261. beforeDestroy() {
  262. // 在组件销毁前移除beforeunload事件监听器
  263. window.removeEventListener('load', this.handlePageRefresh);
  264. },
  265. mounted() {
  266. },
  267. methods: {
  268. handlePageRefresh(){
  269. let url = this.urlPrefix + "/chatRoom/cleanAllChatRoomData"
  270. let uuids = [];
  271. // uuids.push(this.userFirst.uuid)
  272. // uuids.push(this.userSecond.uuid)
  273. // uuids.push(this.userThird.uuid)
  274. // console.log(uuids)
  275. // this.$post(url,uuids,null,resp => {
  276. // let res = resp.data
  277. // if(res.code == 200){
  278. // }else{
  279. // }
  280. // })
  281. },
  282. //第一个用户聊天室
  283. userFirstSelectUserListHandle(){//获取当前可登录用户
  284. this.getUserListHandle(this.userFirst)
  285. },
  286. async userFirstOnlineHandle(){//用户上线和下线
  287. //如果已经在线,则是下线操作
  288. if(this.userFirst.isOnline){
  289. this.userOffline(this.userFirst)
  290. Object.assign(this.userFirst, this.$options.data().userFirst)
  291. return
  292. }
  293. //上线操作
  294. if(!(this.userFirst.uuid == null)){
  295. this.userOnline(this.userFirst)
  296. }
  297. },
  298. userFirstOpenFriendRoomHandle(index,row){//选取好友列表进行聊天
  299. this.userFirst.chatMsgList = []
  300. this.userFirst.openFriend = row
  301. this.userFirst.chatRoomTitle = (row.type == 1 ? "" : "(群)") + row.name
  302. this.openFriendRoomHandle(this.userFirst,row)
  303. },
  304. userFirstSendMsgHandle(){//发送消息
  305. this.sendMsgHandle(this.userFirst)
  306. },
  307. //第二个用户聊天室
  308. userSecondSelectUserListHandle(){//获取当前可登录用户
  309. this.getUserListHandle(this.userSecond)
  310. },
  311. async userSecondOnlineHandle(){//用户上线和下线
  312. //如果已经在线,则是下线操作
  313. if(this.userSecond.isOnline){
  314. this.userOffline(this.userSecond)
  315. Object.assign(this.userSecond, this.$options.data().userSecond)
  316. return
  317. }
  318. //上线操作
  319. if(!(this.userSecond.uuid == null)){
  320. this.userOnline(this.userSecond)
  321. }
  322. },
  323. userSecondOpenFriendRoomHandle(index,row){//选取好友列表进行聊天
  324. this.userSecond.chatMsgList = []
  325. this.userSecond.openFriend = row
  326. this.userSecond.chatRoomTitle = (row.type == 1 ? "" : "(群)") + row.name
  327. this.openFriendRoomHandle(this.userSecond,row)
  328. },
  329. userSecondSendMsgHandle(){//发送消息
  330. this.sendMsgHandle(this.userSecond)
  331. },
  332. //第三个用户聊天室
  333. userThirdSelectUserListHandle(){//获取当前可登录用户
  334. this.getUserListHandle(this.userThird)
  335. },
  336. async userThirdOnlineHandle(){//用户上线和下线
  337. //如果已经在线,则是下线操作
  338. if(this.userThird.isOnline){
  339. this.userOffline(this.userThird)
  340. Object.assign(this.userThird, this.$options.data().userThird)
  341. return
  342. }
  343. //上线操作
  344. if(!(this.userThird.uuid == null)){
  345. this.userOnline(this.userThird)
  346. }
  347. },
  348. userThirdOpenFriendRoomHandle(index,row){//选取好友列表进行聊天
  349. this.userThird.chatMsgList = []
  350. this.userThird.openFriend = row
  351. this.userThird.chatRoomTitle = (row.type == 1 ? "" : "(群)") + row.name
  352. this.openFriendRoomHandle(this.userThird,row)
  353. },
  354. userThirdSendMsgHandle(){//发送消息
  355. this.sendMsgHandle(this.userThird)
  356. },
  357. //公共方法
  358. getUserListHandle(user){//获取可用账号
  359. let url = this.urlPrefix + "/chatRoom/getAllUserList"
  360. this.$post(url,null,null,resp => {
  361. let res = resp.data
  362. if(res.code == 200){
  363. user.allUserList = res.data
  364. }else{
  365. this.$message.error(res.msg)
  366. }
  367. })
  368. },
  369. connetChatRoom(stompClient,user){//websocket连接
  370. return new Promise((resolve, reject) => {
  371. // 设置WebSocket连接以及Stomp客户端方式1
  372. // const socket = new WebSocket('ws://localhost:8080/chat');
  373. // this.stompClient = Stomp.over(socket);
  374. // 创建Stomp客户端方式2
  375. // this.stompClient = Stomp.client('ws://localhost:8083/chat')
  376. // 连接成功的回调函数
  377. const onConnect = (frame) => {
  378. console.log('连接成功:',frame);
  379. resolve(true)
  380. };
  381. // 连接错误的回调函数
  382. const onError = (error) => {
  383. console.log('连接错误:',error);
  384. resolve(false)
  385. };
  386. // 连接断开的回调函数
  387. const onDisconnect = (offLine) => {
  388. console.log('连接断开:',offLine);
  389. };
  390. // 建立连接
  391. stompClient.connect({"Authorization": user.uuid, "user": JSON.stringify(user)}, onConnect, onError);
  392. // 监听客户端断开事件
  393. stompClient.onDisconnect = onDisconnect;
  394. })
  395. },
  396. userOnline(user){//用户上线
  397. let url = this.urlPrefix + "/chatRoom/getUserData"
  398. this.$post(url,{uuid:user.uuid},null,async resp => {
  399. let res = resp.data
  400. if(res.code == 200){
  401. user.stompClient = Stomp.client('ws://localhost:8083/chat')
  402. console.log("连接对象:",user.stompClient)
  403. let connect = await this.connetChatRoom(user.stompClient,{uuid: user.uuid,name: user.userName,type: res.data.user.type})
  404. if(connect){
  405. console.log("返回数据:",res.data)
  406. user.friendList = res.data.friendList
  407. user.uuid = res.data.user.uuid
  408. user.userName = res.data.user.name
  409. // this.userFirst.type = res.data.user.type
  410. user.isOnline = !user.isOnline
  411. // this.subscribeChatRoom(user.stompClient,{uuid:user.uuid,name:user.userName,type:'1'})
  412. }else{
  413. return
  414. }
  415. }else{
  416. this.$message.error(res.msg)
  417. return
  418. }
  419. })
  420. },
  421. userOffline(user){//用户下线
  422. let url = this.urlPrefix + "/chatRoom/offLine"
  423. user.stompClient.disconnect(() => {
  424. console.log(user.uuid,' 下线了!');
  425. //告诉服务器下线通知
  426. this.$post(url,{uuid:user.uuid},null,resp => {
  427. let res = resp.data
  428. if(res.code == 200){
  429. this.$message.success(res.msg)
  430. }else{
  431. this.$message.error(res.msg)
  432. return
  433. }
  434. })
  435. });
  436. user.isOnline = !user.isOnline
  437. },
  438. openFriendRoomHandle(user,row){//打开好友聊天室
  439. if(row.type == 1){
  440. console.log(user.uuid," 当前选中的是好友:",row.name)
  441. var destination = '/own/' + user.uuid + '/' + row.uuid + '/messages';
  442. this.subscribeChatRoomMssages(user,destination)
  443. }else{
  444. console.log(user.uuid," 当前选中的是群:",row.name)
  445. var destination = '/topic/' + row.uuid + '/queue/messages';
  446. //监听来自当前群消息
  447. this.subscribeChatRoomMssages(user,destination)
  448. }
  449. let url = this.urlPrefix + "/chatRoom/getUserRoomMsg"
  450. let userRoomMsg = {
  451. uuid: user.uuid,
  452. roomId: row.uuid,
  453. type: row.type
  454. }
  455. //去获取历史聊天记录
  456. this.$post(url,userRoomMsg,null,resp => {
  457. let res = resp.data
  458. if(res.code == 200){
  459. user.chatMsgList = [...res.data, ...user.chatMsgList]
  460. console.log("历史聊天消息:",user.chatMsgList)
  461. this.scrollToBottom()
  462. }else{
  463. this.$message.error(res.msg)
  464. }
  465. })
  466. },
  467. sendMsgHandle(user){//发送消息
  468. if(user.openFriend.uuid == undefined) {
  469. console.log("发送的消息无接收者,发送者:",user.uuid)
  470. return
  471. }
  472. if(user.sendMsg == '' || user.sendMsg == undefined) {
  473. console.log("发送的消息无数据,发送者:",user.uuid)
  474. this.scrollToBottom()
  475. return
  476. }
  477. let message = {
  478. senderUuid: user.uuid,//发送者uuid,即当前登录用户uuid
  479. senderName: user.userName,//发送者姓名
  480. sendTime: this.$moment().format('MM-DD HH:mm:ss'),//发送时间
  481. sendContent: user.sendMsg,//发送内容
  482. receiverUuid: user.openFriend.uuid,//接受者uuid,选中当前聊天室的用户uuid
  483. receiverName: user.openFriend.name,//接受者名称,选中当前聊天室的用户名称
  484. msgType: user.openFriend.type//消息类型,单聊还是群聊,当前选中当前聊天室的类型
  485. };
  486. console.log(user.uuid," 发送的消息:",JSON.stringify(message))
  487. //如果是群发消息,那就不在添加自己发送的消息到列表
  488. user.openFriend.type == 1 ? user.chatMsgList.push(message) : ''
  489. user.stompClient.send('/app/user.sendMessage', {}, JSON.stringify(message));
  490. user.sendMsg = ''
  491. this.scrollToBottom()
  492. },
  493. subscribeChatRoomMssages(user,destination){//监听聊天室消息
  494. user.subscription = user.stompClient.subscribe(destination, function (message) {
  495. let msg = JSON.parse(message.body)
  496. let info = "新消息 => 当前账号:" + user.uuid + " ; 路径" + destination + " ; 接收者: " + msg.receiverUuid + " ; 发送者: " + msg.senderUuid;
  497. console.log(info)
  498. let chatMsg = {
  499. senderUuid: msg.senderUuid,//发送者uuid
  500. senderName: msg.senderName,//发送者姓名
  501. sendTime: msg.sendTime,//发送时间
  502. sendContent: msg.sendContent,//发送内容
  503. receiverUuid: msg.receiverUuid,//接受者,即当前登录用户uuid
  504. receiverName: msg.receiverName,
  505. msgType: msg.msgType//消息类型,单聊还是群聊
  506. }
  507. if(msg.msgType == 1){
  508. user.openFriend.uuid == msg.senderUuid ? user.chatMsgList.push(chatMsg) : ''
  509. }else{
  510. user.openFriend.uuid == msg.receiverUuid ? user.chatMsgList.push(chatMsg) : ''
  511. }
  512. this.scrollToBottom()
  513. });
  514. },
  515. subscribeChatRoom(stompClient,user){//测试接口
  516. stompClient.subscribe('/topic/public', function (message) {
  517. console.log('/own/测试接口订阅的消息: ' + message.body);
  518. // 处理接收到的消息
  519. });
  520. },
  521. scrollToBottom() {
  522. this.$nextTick(() => {
  523. var container1 = this.$refs.recMsgRef1;
  524. if(container1){
  525. container1.scrollTop = container1.scrollHeight;
  526. }
  527. var container2 = this.$refs.recMsgRef2;
  528. if(container2){
  529. container2.scrollTop = container2.scrollHeight;
  530. }
  531. var container3 = this.$refs.recMsgRef3;
  532. if(container3){
  533. container3.scrollTop = container3.scrollHeight;
  534. }
  535. console.log(container1," = ",container2," = ",container3)
  536. });
  537. }
  538. }
  539. };
  540. </script>
  541. <style lang="less" scoped>
  542. .chatRoomTag{
  543. text-align: center;
  544. width: 100%;
  545. display: flex;
  546. flex-direction: row; /*弹性布局的方向*/
  547. .userTag{
  548. border: 1px red solid;
  549. flex-grow: 1;
  550. height: 800px;
  551. .headerHandleTag{
  552. width: 100%;
  553. display: flex;
  554. // flex-direction: row; /*弹性布局的方向*/
  555. .onlineChatTag{
  556. display: inline-block;
  557. width: 120px;
  558. }
  559. .chatUserTag{
  560. display: inline-block;
  561. width: 320px;
  562. }
  563. .userNameTag{
  564. display: inline-block;
  565. width: 100px;
  566. }
  567. }
  568. .bodyHandleTag{
  569. width: 100%;
  570. display: flex;
  571. .friendListTag{
  572. width: 120px;
  573. }
  574. .chatRoomMsgTag{
  575. // height: 100px;
  576. width: 415px;
  577. .selectLoginUserTag{
  578. margin-top: 100px;
  579. }
  580. .chatMsgTag{
  581. border: 1px red solid;
  582. height: 700px;
  583. .recMsgTag{
  584. list-style-type: none;
  585. list-style: none;
  586. padding-left: 10px;
  587. max-height: 700px;
  588. overflow: scroll;
  589. font-size: 12px;
  590. .pointTag{
  591. display: inline-block;
  592. width: 3px;
  593. height: 6px;
  594. border-radius: 50%;
  595. background-color: #0251fd;
  596. }
  597. }
  598. .sendMsgTag{
  599. display: flex;
  600. }
  601. }
  602. }
  603. }
  604. }
  605. }
  606. .chat-room {
  607. height: 200px;
  608. overflow-y: scroll;
  609. }
  610. </style>

 五、源码和结尾

后端gitee地址:https://gitee.com/java_utils_demo/java-websocket-chat-room-demo.git

前端gitee地址:vue2_demo: 各实现功能的前端页面支撑,采用vue2

总结:

六、附加sendToUser测试代码

候补

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/892388
推荐阅读
相关标签
  

闽ICP备14008679号