springboot socket客户端_天天玩微信,Spring Boot 开发私有即时通信系统了解一下

本文介绍如何使用Spring Boot、Spring Security和WebSocket搭建一个私有的即时通信系统,涉及点对点聊天、群聊功能,并提供交互示例和完整可运行的DEMO代码。
摘要由CSDN通过智能技术生成
点击上方☝ SpringForAll社区  轻松关注! 及时获取有趣有料的技术文章

1/ 概述

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

2/ 所需依赖

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

 1<properties>
2    <java.version>1.8java.version>
3    <thymeleaf.version>3.0.0.RELEASEthymeleaf.version>
4    <thymeleaf-layout-dialect.version>2.0.0thymeleaf-layout-dialect.version>
5  properties>
6
7  <dependencies>
8
9    
10    <dependency>
11      <groupId>org.springframework.bootgroupId>
12      <artifactId>spring-boot-starter-websocketartifactId>
13      <exclusions>
14        <exclusion>
15          <groupId>org.springframework.bootgroupId>
16          <artifactId>spring-boot-starter-tomcatartifactId>
17        exclusion>
18      exclusions>
19    dependency>
20
21    
22    <dependency>
23      <groupId>org.springframework.bootgroupId>
24      <artifactId>spring-boot-starter-undertowartifactId>
25    dependency>
26
27    
28    <dependency>
29      <groupId>org.springframework.bootgroupId>
30      <artifactId>spring-boot-starter-securityartifactId>
31    dependency>
32
33    
34    <dependency>
35      <groupId>org.springframework.bootgroupId>
36      <artifactId>spring-boot-starter-data-mongodbartifactId>
37    dependency>
38
39    
40    <dependency>
41      <groupId>org.springframework.bootgroupId>
42      <artifactId>spring-boot-starter-thymeleafartifactId>
43    dependency>
44
45    <dependency>
46      <groupId>org.projectlombokgroupId>
47      <artifactId>lombokartifactId>
48      <version>1.16.16version>
49    dependency>
50
51    <dependency>
52      <groupId>com.alibabagroupId>
53      <artifactId>fastjsonartifactId>
54      <version>1.2.30version>
55    dependency>
56
57    
58    <dependency>
59      <groupId>org.webjarsgroupId>
60      <artifactId>webjars-locatorartifactId>
61    dependency>
62    <dependency>
63      <groupId>org.webjarsgroupId>
64      <artifactId>sockjs-clientartifactId>
65      <version>1.0.2version>
66    dependency>
67    <dependency>
68      <groupId>org.webjarsgroupId>
69      <artifactId>stomp-websocketartifactId>
70      <version>2.3.3version>
71    dependency>
72    <dependency>
73      <groupId>org.webjarsgroupId>
74      <artifactId>bootstrapartifactId>
75      <version>3.3.7version>
76    dependency>
77    <dependency>
78      <groupId>org.webjarsgroupId>
79      <artifactId>jqueryartifactId>
80      <version>3.1.0version>
81    dependency>
82
83  dependencies>

配置文件内容:

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

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

2807069efa50f57b09bd8007081ce0c0.png
img

程序结构

3/ 创建程序启动类,启用WebSocket

使用@EnableWebSocket注解

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

4/ 配置Spring Security

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

5/ 配置Web Socket(结合第7节的JS看)

 1@Configuration
2@EnableWebSocketMessageBroker
3@Log4j
4public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
5
6  // 此处可注入自己写的Service
7
8  @Override
9  public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
10    // 客户端与服务器端建立连接的点
11    stompEndpointRegistry.addEndpoint("/any-socket").withSockJS();
12  }
13
14  @Override
15  public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
16    // 配置客户端发送信息的路径的前缀
17    messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
18    messageBrokerRegistry.enableSimpleBroker("/topic");
19  }
20
21  @Override
22  public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
23    registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
24      @Override
25      public WebSocketHandler decorate(final WebSocketHandler handler) {
26        return new WebSocketHandlerDecorator(handler) {
27          @Override
28          public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
29            // 客户端与服务器端建立连接后,此处记录谁上线了
30            String username = session.getPrincipal().getName();
31            log.info("online: " + username);
32            super.afterConnectionEstablished(session);
33          }
34
35          @Override
36          public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
37            // 客户端与服务器端断开连接后,此处记录谁下线了
38            String username = session.getPrincipal().getName();
39            log.info("offline: " + username);
40            super.afterConnectionClosed(session, closeStatus);
41          }
42        };
43      }
44    });
45    super.configureWebSocketTransport(registration);
46  }
47}

6/ 点对点消息,群消息

 1@Controller
2@Log4j
3public class ChatController {
4
5  @Autowired
6  private SimpMessagingTemplate template;
7
8  // 注入其它Service
9
10  // 群聊天
11  @MessageMapping("/notice")
12  public void notice(Principal principal, String message) {  
13    // 参数说明 principal 当前登录的用户, message 客户端发送过来的内容
14    // principal.getName() 可获得当前用户的username  
15
16    // 发送消息给订阅 "/topic/notice" 且在线的用户
17    template.convertAndSend("/topic/notice", message); 
18  }
19
20  // 点对点聊天
21  @MessageMapping("/chat")
22  public void chat(Principal principal, String message){
23    // 参数说明 principal 当前登录的用户, message 客户端发送过来的内容(应该至少包含发送对象toUser和消息内容content)
24    // principal.getName() 可获得当前用户的username
25
26    // 发送消息给订阅 "/user/topic/chat" 且用户名为toUser的用户
27    template.convertAndSendToUser(toUser, "/topic/chat", content);
28  }
29
30}

7/ 客户端与服务器端交互

 1var stompClient = null;
2
3    function connect() {
4        var socket = new SockJS('/any-socket');
5        stompClient = Stomp.over(socket);
6        stompClient.connect({}, function (frame) {
7            // 订阅 /topic/notice 实现群聊
8            stompClient.subscribe('/topic/notice', function (message) {
9                showMessage(JSON.parse(message.body));
10            });
11            // 订阅 /user/topic/chat 实现点对点聊
12            stompClient.subscribe('/user/topic/chat', function (message) {
13                showMessage(JSON.parse(message.body));
14            });
15        });
16    }
17
18    function showMessage(message) {
19        // 处理消息在页面的显示
20    }
21
22    $(function () {
23        // 建立websocket连接
24        connect();
25        // 发送消息按钮事件
26        $("#send").click(function () {
27            if (target == "TO_ALL"){
28                // 群发消息
29                // 匹配后端ChatController中的 @MessageMapping("/notice")
30                stompClient.send("/app/notice", {}, '消息内容');
31            }else{
32                // 点对点消息,消息中必须包含对方的username
33                // 匹配后端ChatController中的 @MessageMapping("/chat")
34                var content = "{'content':'消息内容','receiver':'anoy'}";
35                stompClient.send("/app/chat", {}, content);
36            }
37        });
38    });

8/ 效果测试

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

53fd0052a5fdfd4c25b0548b034bdfbe.png
img

超级管理员

308023eaf5e28dd77b5a545ef61d6d8e.png
img

Anoyi

feecb01e30a9dc4d3ca1a4a45229962d.png
img

Jock

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

eabbe0ef8a3d3c5d482636a429278589.png
img

Jock

023e92a8ac5abcfd216a618c268f9769.png
img

超级管理员

9c1370e7a05ffe70314e6ca60094bc67.png
img

Anoyi

9/ 轻量级DEMO(完整可运行代码)

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

10/ 参考文献

  • spring-mongodb 官方文档

  • Spring Framework 官方文档

  • Spring Guide - stomp websocket

© 著作权归作者所有,转载或内容合作请联系作者

有任何问题,请留言告诉我们哈。

a9943c110978eeaccafd16ab09a3b873.gif

● Spring Boot 定制 parent 快速构建应用

● Spring Boot 容器化部署 - Docker

● SpringBot中教你手把手配置 https

● Spring Boot 日志处理你还在用Logback?

● 【双11狂欢的背后】微服务注册中心如何承载大型系统的千万级访问?

● Spring Boot 新一代监控你该这么玩

● Spring Boot 异常处理

● Spring Boot 配置 - 配置信息加密

● 拒绝黑盒应用-Spring Boot 应用可视化监控

● 并发Bug之源有三,请睁大眼睛看清它们

a8a2c58e3b17de5fae2d1a8fcb5f3ab8.png

be50e668f162aec7144460743c1181df.gif

如有收获,请帮忙转发,您的鼓励是作者最大的动力,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值