preface

In this article, we will further explain how to configure WebSocket in SpringBoot based on THE WSS protocol and STOMP. This article assumes that you have some knowledge of STOMP, otherwise you are advised to learn about STOMP first. You can refer to this article. In addition, unlike the previous code examples, which are quite complex, this article will show you the effect with as little code as possible.

Results show

As in the previous article, before showing the actual code configuration, let’s show the final result:

Here is the directory structure for the entire project:

├ ─ the main │ ├ ─ Java │ │ └ ─ com │ │ └ ─ ZJW │ │ └ ─ stomp │ │ │ StompApplication. Java │ │ │ │ │ ├ ─ config │ │ │ │ ├ ─ podController │ ├ ─ BroadcastController. │ ├ ─ podController │ ├ ─ podController Htmlcontroller. Java │ │ ├ ─ garbage resources │ application. Yaml │ ├ ─ keystore │ └ ─ test └ ─ Java └ ─ com └ ─ ZJW └ ─ stomp StompApplicationTests. JavaCopy the code

Tips

To generate the above structure of the directory tree, simply use the tree /f folder name on the command line. If you do not want to display specific files, remove the /f parameter.

Specific configuration

wssconfiguration

To configure the WSS protocol, SpringBoot can configure HTTPS. Here are the steps:

  1. Generating a Signing Certificate

    In CMD, enter D:\develop\keystore. JKS, which is the path to generate the certificate. Change the path according to your own requirements.

    keytool -genkeypair -alias tomcat -keyalg RSA -keystore D:\develop\keystore.jks
    Copy the code
  2. Project configuration

    First copy the keystore.jks file you just generated and paste it into the Resources folder. When you are done, modify the application.yaml(yML) file:

    server:
      port: 443
      ssl.key-store: classpath:keystore.jks
      ssl.key-store-password: 123456
      ssl.key-password: 123456
      ssl.key-alias: tomcat
    Copy the code

    If it is a properties file, change it to the following form:

    server.port=443
    server.ssl.key-store=classpath:keystore.jks
    server.ssl.key-store-password=123456
    server.ssl.key-password=123456
    server.ssl.key-alias=tomcat
    Copy the code
  3. Tomcat configuration

    import org.apache.catalina.connector.Connector;
    import org.apache.tomcat.websocket.server.WsSci;
    import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
    import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
    import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class TomcatConfiguration {
    
        @Bean
        public ServletWebServerFactory servletContainer(a) {
            TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
            tomcat.addAdditionalTomcatConnectors(createSslConnector());
            return tomcat;
        }
    
        private Connector createSslConnector(a) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setScheme("http");
            connector.setPort(8080);
            connector.setSecure(false);
            // Listen for port 8080 to forward to port 443
            connector.setRedirectPort(443);
            return connector;
        }
    
        @Bean
        public TomcatContextCustomizer tomcatContextCustomizer(a) {
            return context -> context.addServletContainerInitializer(new WsSci(), null); }}Copy the code
  4. Browser testing

    After the preceding steps are complete, enter https://localhost/ in the address box of the browser. If the message “insecure” is displayed in the address box, the HTTPS configuration is successful.

STOMPconfiguration

After configuring WSS, which is also equivalent to HTTPS, you can start configuring STOMP:

  1. Introduction of depend on

    The following necessary dependencies need to be introduced first:

    <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-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>webjars-locator</artifactId>
        <version>0.34</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>stomp-websocket</artifactId>
        <version>2.3.3</version>
    </dependency>
    Copy the code
  2. Configure the Controller for broadcasting

    import org.springframework.messaging.handler.annotation.MessageMapping;
    import org.springframework.messaging.handler.annotation.SendTo;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class BroadcastController {
    
        // MessageMapping is @requestMapping.
        // When a message is sent to /sendMsg (the MSG parameter in broardcast is the message sent by the client),
        // The data returned by the broadcast method will be sent to all clients subscribed to /broadcast/greet
        // How to subscribe /broadcast/greet will be seen later in the client code
        @MessageMapping("/sendMsg")
        @SendTo("/broadcast/greet")
        public String broadcast(String msg) {
            returnmsg; }}Copy the code
  3. Configure the WebSocket message proxy

    import org.springframework.context.annotation.Configuration;
    import org.springframework.messaging.simp.config.MessageBrokerRegistry;
    import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
    import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
    import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
    
    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            // Start a simple memory-based message broker
            // Returns the message to the destination client subscribed with the /broadcast prefix
            // The address in @sendto should be prefixed with /broadcast
            config.enableSimpleBroker("/broadcast");
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            // Register a websocket terminal for /websocket
            registry.addEndpoint("/websocket"); }}Copy the code
  4. View Resolution Controller

    Index.html and greet.html are in the templates folder for your convenience. Here you need to configure view parsing:

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HTMLController {
    
        @RequestMapping("/index")
        public String index(a) {
            return "index";
        }
    
        @RequestMapping("/greet")
        public String greet(a) {
            return "greet"; }}Copy the code
  5. The home page code

    <! DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>The home page</title>
        <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    </head>
    <body>
        <div id="greet"></div>
        <script>
    
            / / set the WebSocket connection address WSS: / / localhost/WebSocket
            let socket = new WebSocket('wss://localhost/websocket')
            let stompClient = Stomp.over(socket)
            stompClient.connect({}, function () {
                // Subscribe to /broadcast/greet, that is, the address configured in @sendto
                stompClient.subscribe('/broadcast/greet'.function (frame) {
                    
             
    showGreeting('Received the message:${frame.body}`)})})function showGreeting(clientMessage) { document.getElementById("greet").innerText += `${clientMessage}\n` }
    </script> </body> </html> Copy the code
  6. Send message interface code

    <! DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>A mass of information</title>
        <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    </head>
    <body>
        <label><input type="text" id="msg"/></label>
        <button onclick="sendMsg()">send</button>
        <script>
    
            / / set the WebSocket connection address WSS: / / localhost/WebSocket
            let socket = new WebSocket('wss://localhost/websocket')
            let stompClient = Stomp.over(socket);
    
            function sendMsg() {
                const msg = document.getElementById('msg').value
                // Send the information in the input box, /sendMsg is the address configured in @messagemapping
                stompClient.send("/sendMsg", {}, msg)
                alert('Sent successfully')}</script>
    </body>
    </html>
    Copy the code

    After completing the above configuration, the effect in the effect display can be realized.

conclusion

This article shows you how to use WebSocket integrated with WSS and STOMP in a simple demo that will hopefully help you, and will follow up with some more detailed and complete examples of WebSocket usage.