温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot中怎么使用WebSocket实现点对点消息

发布时间:2022-04-06 16:13:32 来源:亿速云 阅读:231 作者:iii 栏目:移动开发

本篇内容介绍了“SpringBoot中怎么使用WebSocket实现点对点消息”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

一、添加依赖,配置

使用 Spring Security 里的用户。

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-security</artifactId> </dependency>

我们现在需要配置用户信息和权限配置。

@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter {     // 指定密码的加密方式     @SuppressWarnings("deprecation")     @Bean     PasswordEncoder passwordEncoder(){         // 不对密码进行加密         return NoOpPasswordEncoder.getInstance();     }     // 配置用户及其对应的角色     @Override     protected void configure(AuthenticationManagerBuilder auth) throws Exception {         auth.inMemoryAuthentication()                 .withUser("admin").password("123").roles("ADMIN","USER")                 .and()                 .withUser("hangge").password("123").roles("USER");     }     // 配置 URL 访问权限     @Override     protected  void configure(HttpSecurity http) throws Exception {         http.authorizeRequests() // 开启 HttpSecurity 配置                 .anyRequest().authenticated() // 用户访问所有地址都必须登录认证后访问                 .and().formLogin().permitAll(); // 开启表单登录     } }

二、编写WebSocket 配置

@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {     @Override     public void configureMessageBroker(MessageBrokerRegistry config) {         // 设置消息代理的前缀,如果消息的前缀为"/queue",就会将消息转发给消息代理(broker)         // 再由消息代理广播给当前连接的客户端         //也可设置多个 broker,如:config.enableSimpleBroker("/topic","/queue");         config.enableSimpleBroker("/queue");         // 下面方法可以配置一个或多个前缀,通过这些前缀过滤出需要被注解方法处理的消息。         // 例如这里表示前缀为"/app"的destination可以通过@MessageMapping注解的方法处理         // 而其他 destination(例如"/topic""/queue")将被直接交给 broker 处理         config.setApplicationDestinationPrefixes("/app");     }     @Override     public void registerStompEndpoints(StompEndpointRegistry registry) {         // 定义一个前缀为"/chart"的endpoint,并开启 sockjs 支持。         // sockjs 可以解决浏览器对WebSocket的兼容性问题,客户端将通过这里配置的URL建立WebSocket连接         registry.addEndpoint("/chat").withSockJS();     } }

三、编写案例代码

1、编写实体

@Data public class Chat {     // 消息的目标用户     private String to;     // 消息的来源用户     private String from;     // 消息的主体内容     private String content; }

2、编写Controller

@Controller public class DemoController {     @Autowired     SimpMessagingTemplate messagingTemplate;     // 处理来自"/app/chat"路径的消息     @MessageMapping("/chat")     public void chat(Principal principal, Chat chat) {         // 获取当前登录用户的用户名         String from = principal.getName();         // 将用户设置给chat对象的from属性         chat.setFrom(from);         // 再将消息发送出去,发送的目标用户就是 chat 对象的to属性值         messagingTemplate.convertAndSendToUser(chat.getTo(),                 "/queue/chat", chat);     } }

四、编写页面

在 resources/static 目录下创建 chat2.html 页面作为点对点的聊天页面。

连接成功后,订阅的地址为“/user/queue/chat”,该地址比服务端配置的地址多了“/user”前缀,这是因为 SimpMessagingTemplate 类中自动添加了路径前缀。

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>单聊</title>     <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script>     <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.1.2/sockjs.min.js"></script>     <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>     <script>         var stompClient = null;         // 建立一个WebSocket连接         function connect() {             // 首先使用 SockJS 建立连接             var socket = new SockJS('/chat');             // 然后创建一个STOMP实例发起连接请求             stompClient = Stomp.over(socket);             // 连接成功回调             stompClient.connect({}, function (frame) {                 // 订阅服务端发送回来的消息                 stompClient.subscribe('/user/queue/chat', function (chat) {                     // 将服务端发送回来的消息展示出来                     showGreeting(JSON.parse(chat.body));                 });             });         }         // 发送消息         function sendMsg() {             stompClient.send("/app/chat", {},                 JSON.stringify({'content':$("#content").val(),                     'to':$("#to").val()}));         }         // 将服务端发送回来的消息展示出来         function showGreeting(message) {             $("#chatsContent")                 .append("<div>" + message.from+":"+message.content + "</div>");         }         // 页面加载后进行初始化动作         $(function () {             // 页面加载完毕后自动连接             connect();             $( "#send" ).click(function() { sendMsg(); });         });     </script> </head> <body> <div id="chat">     <div id="chatsContent">     </div>     <div>         请输入聊天内容:         <input type="text" id="content" placeholder="聊天内容">         目标用户:         <input type="text" id="to" placeholder="目标用户">         <button id="send" type="button">发送</button>     </div> </div> </body> </html>

五、验证结果

我们使用了 Spring Security 会自动跳转到默认登录页面。

SpringBoot中怎么使用WebSocket实现点对点消息

这里我们配置两个用户信息:admin/123,piao/123。

SpringBoot中怎么使用WebSocket实现点对点消息

SpringBoot中怎么使用WebSocket实现点对点消息

“SpringBoot中怎么使用WebSocket实现点对点消息”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI