SpringBoot中怎么使用WebSocket实现点对点消息(springboot,websocket,移动开发)

时间:2024-04-28 00:49:41 作者 : 石家庄SEO 分类 : 移动开发
  • TAG :

一、添加依赖,配置

使用Spring Security 里的用户。

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

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

@ConfigurationpublicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{//指定密码的加密方式@SuppressWarnings("deprecation")@BeanPasswordEncoderpasswordEncoder(){//不对密码进行加密returnNoOpPasswordEncoder.getInstance();}//配置用户及其对应的角色@Overrideprotectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{auth.inMemoryAuthentication().withUser("admin").password("123").roles("ADMIN","USER").and().withUser("hangge").password("123").roles("USER");}//配置URL访问权限@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests()//开启HttpSecurity配置.anyRequest().authenticated()//用户访问所有地址都必须登录认证后访问.and().formLogin().permitAll();//开启表单登录}}

二、编写WebSocket 配置

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

三、编写案例代码

1、编写实体

@DatapublicclassChat{//消息的目标用户privateStringto;//消息的来源用户privateStringfrom;//消息的主体内容privateStringcontent;}

2、编写Controller

@ControllerpublicclassDemoController{@AutowiredSimpMessagingTemplatemessagingTemplate;//处理来自"/app/chat"路径的消息@MessageMapping("/chat")publicvoidchat(Principalprincipal,Chatchat){//获取当前登录用户的用户名Stringfrom=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 类中自动添加了路径前缀。

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

五、验证结果

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

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

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

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

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

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:SpringBoot中怎么使用WebSocket实现点对点消息的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:SpringBoot怎么使用WebSocket实现群发消息下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18