Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use WebSocket to realize Point-to-Point message in SpringBoot

2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to use WebSocket to achieve peer-to-peer messaging in SpringBoot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First, add dependencies and configure

Use users in Spring Security.

Org.springframework.boot spring-boot-starter-security

We now need to configure user information and permissions configuration.

@ Configurationpublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {/ / specify the password encryption method @ SuppressWarnings ("deprecation") @ Bean PasswordEncoder passwordEncoder () {/ / do not encrypt the password return NoOpPasswordEncoder.getInstance () } / / configure the user and its corresponding role @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication () .withUser ("admin") .password ("123") .roles (" ADMIN "," USER ") .and () .withUser (" hangge ") .password (" 123") .roles ("USER") } / / configure URL access @ Override protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () / / enable HttpSecurity configuration .anyRequest () .authenticated () / / users must log in to all addresses and visit .and () .formLogin () .permitAll (); / / Open form login}}

2. Write WebSocket configuration

@ Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@ Override public void configureMessageBroker (MessageBrokerRegistry config) {/ / sets the prefix of the message broker. If the prefix of the message is "/ queue", the message will be forwarded to the message broker (broker) / / and broadcast to the currently connected client / / multiple broker can also be set, such as: config.enableSimpleBroker ("/ topic", "/ queue") Config.enableSimpleBroker ("/ queue"); / / the following method can configure one or more prefixes to filter out messages that need to be processed by the annotation method. / / for example, it means that the destination with the prefix "/ app" can be processed by @ MessageMapping annotation, while other destination (such as "/ topic"/ queue") will be directly handed over to the broker processing config.setApplicationDestinationPrefixes ("/ app");} @ Override public void registerStompEndpoints (StompEndpointRegistry registry) {/ / define an endpoint with the prefix "/ chart" and enable sockjs support. / / sockjs can solve the problem of browser compatibility with WebSocket. The client will establish a WebSocket connection registry.addEndpoint ("/ chat") .withSockJS ();} through the URL configured here.

Third, write the case code

1. Write entities

@ Datapublic class Chat {/ / the target user of the message private String to; / / the source user of the message private String from; / / the main content of the message private String content;}

2. Write Controller

@ Controllerpublic class DemoController {@ Autowired SimpMessagingTemplate messagingTemplate; / / processes messages from the "/ app/chat" path @ MessageMapping ("/ chat") public void chat (Principal principal, Chat chat) {/ / gets the user name of the currently logged-in user String from = principal.getName (); / / sets the user to the from property chat.setFrom (from) of the chat object / / then send the message to the target user is the to attribute value messagingTemplate.convertAndSendToUser (chat.getTo (), "/ queue/chat", chat) of the chat object;}}

Fourth, write a page

Create a chat2.html page in the resources/static directory as a peer-to-peer chat page.

After a successful connection, the subscribed address is "/ user/queue/chat", which has more "/ user" prefix than the address configured by the server, because the path prefix is automatically added to the SimpMessagingTemplate class.

Single chat var stompClient = null; / / establish a WebSocket connection function connect () {/ / first use SockJS to establish a connection var socket = new SockJS ('/ chat'); / / then create an STOMP instance to initiate a connection request stompClient = Stomp.over (socket) / / callback stompClient.connect ({}, function (frame) {/ / subscribe to the message stompClient.subscribe ('/ user/queue/chat') sent back by the server after a successful connection Function (chat) {/ / display the message sent back by the server to showGreeting (JSON.parse (chat.body)) });});} / send message function sendMsg () {stompClient.send ("/ app/chat", {}, JSON.stringify ({'content':$ ("# content"). Val (),' to':$ ("# to"). Val () } / / display function showGreeting (message) {$("# chatsContent") .append ("" + message.from+ ":" + message.content + "") Initialize the page after loading $(function () {/ / automatically connect connect (); $("# send") .click (function () {sendMsg ();});}) Please enter chat content: target user: send

5. Verification results

If we use Spring Security, we will automatically jump to the default login page.

Here we configure two user information: admin/123,piao/123.

This is the end of the introduction of "how to use WebSocket to implement peer-to-peer messaging in SpringBoot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report