This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Websocket point-to-point communication

  • Configure the POM file
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope> </dependency> <! -- https://mvnrepository.com/artifact/org.webjars/sockjs-client --> <dependency> <groupId>org.webjars</groupId> < artifactId > sockjs - client < / artifactId > < version > 1.1.2 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.webjars/stomp-websocket --> <dependency> <groupId>org.webjars</groupId> < artifactId > stomp - websocket < / artifactId > < version > 2.3.3 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.webjars/jquery --> <dependency> <groupId>org.webjars</groupId> The < artifactId > jquery < / artifactId > < version > 3.5.1 track of < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.webjars/webjars-locator-core --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>Copy the code
  • WebsocketConfig registers breakpoints

implements WebSocketMessageBrokerConfigurer

  • WebsocketConfig Enables SocketJS support
public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOriginPatterns("http://localhost:8080").withSockJS();
    }
Copy the code
  • A WebsocketConfig prefix with /topic will forward the message to the message broker
public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic","/queue");
    }
Copy the code
  • SecurityConfig Writes the account password
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("{noop}admin123")
                .roles("admin")
                .and()
                .withUser("root")
                .password("{noop}123")
                .roles("admin")
                .and()
                .withUser("test")
                .password("{noop}admin123")
                .roles("admin");
    }
Copy the code
  • GreetingController
MessageMapping("/hello") // Message address @sendto ("/topic/greeting") // Forward the broadcast address. The front-end listens for received messagesCopy the code
  • GreetingController chat
  • Principal User information
  • A specific message from Param Chat
public void chat(Principal principal, Chat chat) {
        String name = principal.getName();
        chat.setFrom(name);
        messagingTemplate.convertAndSendToUser(chat.getTo(),"/queue/chat",chat);
    }
Copy the code
  • entity Chat
private String to; // Private String from; // Private String content; // The content of the message // expand the getter and the setter methodCopy the code
  • HTML
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/webjars/jquery/jquery.min.js"></script> <script src="/webjars/sockjs-client/sockjs.min.js"></script> <script src="/webjars/stomp-websocket/stomp.min.js"></script> </head> <body> <div> <input id="username" type="text" Placeholder ="text" > <div> <input type="text" id="content"> </button id="send" type="button"> </div> <div id="chat" style="border:5px solid #000"></div> <script> var stompClient; $(function () { connect(); $('#send').click(function () {// click to send stompclient.send ('/online_chat',{}, json.stringify ({ 'to':$('#username').val(), $('#content').val()})})}) function connect() {var socketjs = new SockJS("/chat"); // Specify the endpoint stompClient = stomp.over (socketjs); Websocket stompClient.connect({},function (frame) {// Establish connection stompClient.subscribe('/user/queue/chat',function (greeting) { var msgBody = JSON.parse(greeting.body); $('#chat').append('<div>'+msgBody.from+' : '+ msgBody.content +'</div>') }) }) } </script> </body> </html>Copy the code

Step by step leisurely implementation of Websocket1 to 1 communication!