利用Spring Boot作为基础框架,Spring Security作为安全框架,WebSocket作为通信框架,实现点对点聊天和群聊天。

Spring Boot 版本 1.5.3,使用MongoDB存储数据(非必须),Maven依赖如下:

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
  4. <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
  5. </properties>
  6. <dependencies>
  7. <!-- WebSocket依赖,移除Tomcat容器 -->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-websocket</artifactId>
  11. <exclusions>
  12. <exclusion>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-tomcat</artifactId>
  15. </exclusion>
  16. </exclusions>
  17. </dependency>
  18. <!-- 使用Undertow容器 -->
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-undertow</artifactId>
  22. </dependency>
  23. <!-- Spring Security 框架 -->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-security</artifactId>
  27. </dependency>
  28. <!-- MongoDB数据库 -->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  32. </dependency>
  33. <!-- Thymeleaf 模版引擎 -->
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.projectlombok</groupId>
  40. <artifactId>lombok</artifactId>
  41. <version>1.16.16</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>com.alibaba</groupId>
  45. <artifactId>fastjson</artifactId>
  46. <version>1.2.30</version>
  47. </dependency>
  48. <!-- 静态资源 -->
  49. <dependency>
  50. <groupId>org.webjars</groupId>
  51. <artifactId>webjars-locator</artifactId>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.webjars</groupId>
  55. <artifactId>sockjs-client</artifactId>
  56. <version>1.0.2</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.webjars</groupId>
  60. <artifactId>stomp-websocket</artifactId>
  61. <version>2.3.3</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.webjars</groupId>
  65. <artifactId>bootstrap</artifactId>
  66. <version>3.3.7</version>
  67. </dependency>
  68. <dependency>
  69. <groupId>org.webjars</groupId>
  70. <artifactId>jquery</artifactId>
  71. <version>3.1.0</version>
  72. </dependency>
  73. </dependencies>

配置文件内容:

  1. server:
  2. port: 80
  3. # 若使用MongoDB则配置如下参数
  4. spring:
  5. data:
  6. mongodb:
  7. uri: mongodb://username:password@172.25.11.228:27017
  8. authentication-database: admin
  9. database: chat

大致程序结构,仅供参考:

程序结构

使用@EnableWebSocket注解

  1. @SpringBootApplication
  2. @EnableWebSocket
  3. public class Application {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Application.class, args);
  6. }
  7. }

此章节省略。(配置好Spring Security,用户能正常登录即可)
可以参考:Spring Boot 全栈开发:用户安全

  1. @Configuration
  2. @EnableWebSocketMessageBroker
  3. @Log4j
  4. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
  5. // 此处可注入自己写的Service
  6. @Override
  7. public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
  8. // 客户端与服务器端建立连接的点
  9. stompEndpointRegistry.addEndpoint("/any-socket").withSockJS();
  10. }
  11. @Override
  12. public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
  13. // 配置客户端发送信息的路径的前缀
  14. messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
  15. messageBrokerRegistry.enableSimpleBroker("/topic");
  16. }
  17. @Override
  18. public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
  19. registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
  20. @Override
  21. public WebSocketHandler decorate(final WebSocketHandler handler) {
  22. return new WebSocketHandlerDecorator(handler) {
  23. @Override
  24. public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
  25. // 客户端与服务器端建立连接后,此处记录谁上线了
  26. String username = session.getPrincipal().getName();
  27. log.info("online: " + username);
  28. super.afterConnectionEstablished(session);
  29. }
  30. @Override
  31. public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
  32. // 客户端与服务器端断开连接后,此处记录谁下线了
  33. String username = session.getPrincipal().getName();
  34. log.info("offline: " + username);
  35. super.afterConnectionClosed(session, closeStatus);
  36. }
  37. };
  38. }
  39. });
  40. super.configureWebSocketTransport(registration);
  41. }
  42. }
  1. @Controller
  2. @Log4j
  3. public class ChatController {
  4. @Autowired
  5. private SimpMessagingTemplate template;
  6. // 注入其它Service
  7. // 群聊天
  8. @MessageMapping("/notice")
  9. public void notice(Principal principal, String message) {
  10. // 参数说明 principal 当前登录的用户, message 客户端发送过来的内容
  11. // principal.getName() 可获得当前用户的username
  12. // 发送消息给订阅 "/topic/notice" 且在线的用户
  13. template.convertAndSend("/topic/notice", message);
  14. }
  15. // 点对点聊天
  16. @MessageMapping("/chat")
  17. public void chat(Principal principal, String message){
  18. // 参数说明 principal 当前登录的用户, message 客户端发送过来的内容(应该至少包含发送对象toUser和消息内容content)
  19. // principal.getName() 可获得当前用户的username
  20. // 发送消息给订阅 "/user/topic/chat" 且用户名为toUser的用户
  21. template.convertAndSendToUser(toUser, "/topic/chat", content);
  22. }
  23. }
  1. var stompClient = null;
  2. function connect() {
  3. var socket = new SockJS('/any-socket');
  4. stompClient = Stomp.over(socket);
  5. stompClient.connect({}, function (frame) {
  6. // 订阅 /topic/notice 实现群聊
  7. stompClient.subscribe('/topic/notice', function (message) {
  8. showMessage(JSON.parse(message.body));
  9. });
  10. // 订阅 /user/topic/chat 实现点对点聊
  11. stompClient.subscribe('/user/topic/chat', function (message) {
  12. showMessage(JSON.parse(message.body));
  13. });
  14. });
  15. }
  16. function showMessage(message) {
  17. // 处理消息在页面的显示
  18. }
  19. $(function () {
  20. // 建立websocket连接
  21. connect();
  22. // 发送消息按钮事件
  23. $("#send").click(function () {
  24. if (target == "TO_ALL"){
  25. // 群发消息
  26. // 匹配后端ChatController中的 @MessageMapping("/notice")
  27. stompClient.send("/app/notice", {}, '消息内容');
  28. }else{
  29. // 点对点消息,消息中必须包含对方的username
  30. // 匹配后端ChatController中的 @MessageMapping("/chat")
  31. var content = "{'content':'消息内容','receiver':'anoy'}";
  32. stompClient.send("/app/chat", {}, content);
  33. }
  34. });
  35. });

登录三个用户:Anoyi、Jock、超级管理员。
群消息测试,超级管理员群发消息:

超级管理员

Anoyi

Jock

点对点消息测试,Anoyi给Jock发送消息,只有Jock收到消息,Anoyi和超级管理员收不到消息:

Jock

超级管理员

Anoyi

Spring Boot 开发私有即时通信系统(WebSocket)(续)

Java 资料大全 链接:https://pan.baidu.com/s/1pUCCPstPnlGDCljtBVUsXQ 密码:b2xc
更多资料: 2020 年 精选阿里 Java、架构、微服务精选资料等,加 v ❤ :qwerdd111

转载,请保留原文地址,谢谢 ~

版权声明:本文为Alandre原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/Alandre/p/12953591.html