Summary of using WebSocket in Spring Boot

Introduction

The so-called WebSocket, similar to Socket, its function is to allow the client and server in the Web application to establish full-duplex communication. There are generally three ways to use WebSocket in Spring-based applications:
• Use the @ServerEndpoint annotation provided by Java to implement
• Use the low-level WebSocket API provided by Spring to implement
• Use STOMP message implementation

Use the @ServerEndpoint annotation provided by Java to achieve

(1) Use the @ServerEndpoint annotation to monitor a WebSocket request path:
here, the client's connection port/reverse is monitored, and how to handle the message sent by the client is defined

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
/**
 * ReverseWebSocketEndpoint
 *
 * @author zifangsky
 * @date 2018/9/30
 * @since 1.0.0
 */
@ServerEndpoint("/reverse")
public class ReverseWebSocketEndpoint {
    @OnMessage
    public void handleMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse());
    }
}
(2)WebSocket相关配置:
package cn.zifangsky.samplewebsocket.config;
 
import cn.zifangsky.samplewebsocket.websocket.ReverseWebSocketEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
/**
 * WebSocket相关配置
 *
 * @author zifangsky
 * @date 2018/9/30
 * @since 1.0.0
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig{
 
    @Bean
    public ReverseWebSocketEndpoint reverseWebSocketEndpoint() {
        return new ReverseWebSocketEndpoint();
    }
 
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
 
}

(3) Sample page:

<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>WebSocket Examples: Reverse</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }
 
        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
 
        .layui-btn {
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        var ws = null;
 
        $(function () {
            var target = $("#target");
            if (window.location.protocol === 'http:') {
                target.val('ws://' + window.location.host + target.val());
            } else {
                target.val('wss://' + window.location.host + target.val());
            }
        });
 
        function setConnected(connected) {
            var connect = $("#connect");
            var disconnect = $("#disconnect");
            var reverse = $("#reverse");
 
            if (connected) {
                connect.addClass("layui-btn-disabled");
                disconnect.removeClass("layui-btn-disabled");
                reverse.removeClass("layui-btn-disabled");
            } else {
                connect.removeClass("layui-btn-disabled");
                disconnect.addClass("layui-btn-disabled");
                reverse.addClass("layui-btn-disabled");
            }
 
            connect.attr("disabled", connected);
            disconnect.attr("disabled", !connected);
            reverse.attr("disabled", !connected);
        }
 
        //连接
        function connect() {
            var target = $("#target").val();
 
            ws = new WebSocket(target);
            ws.onopen = function () {
                setConnected(true);
                log('Info: WebSocket connection opened.');
            };
            ws.onmessage = function (event) {
                log('Received: ' + event.data);
            };
            ws.onclose = function () {
                setConnected(false);
                log('Info: WebSocket connection closed.');
            };
        }
 
        //断开连接
        function disconnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
            setConnected(false);
        }
 
        //文字反转
        function reverse() {
            if (ws != null) {
                var message = $("#message").val();
                log('Sent: ' + message);
                ws.send(message);
            } else {
                alert('WebSocket connection not established, please connect.');
            }
        }
 
        //日志输出
        function log(message) {
            console.debug(message);
        }
    </script>
</head>
<body>
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
        enabled. Please enable
        Javascript and reload this page!</h2></noscript>
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>Reverse</legend>
            <div>
                <input id="target" type="text" class="layui-input" size="40" style="width: 350px" value="/reverse"/>
            </div>
            <div>
                <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
                <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="disconnect();">Disconnect
                </button>
 
            </div>
            <div>
                <textarea id="message" class="layui-textarea" placeholder="请输入需要反转的内容" style="width: 350px"></textarea>
            </div>
            <div>
                <button id="reverse" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="reverse();">Reverse message
                </button>
            </div>
        </div>
    </div>
</body>
</html>

Visit the page after starting the project, the effect is as follows:

Use the low-level WebSocket API implementation provided by Spring

Spring 4.0 provides support for WebSocket communication, including:
• Low-level API
for sending and receiving messages;
High -level API for sending and receiving messages; • Templates for sending messages;
• Support for SockJS to solve browser and server And the problem that the proxy does not support WebSocket.
Using the low-level API provided by Spring to implement WebSocket requires the following steps:
(1) Add a WebSocketHandler:
define a message processing class that inherits the AbstractWebSocketHandler class, and then customize the "connection establishment" and "receive/send messages" , "Abnormal situation" and other situations to deal with

package cn.zifangsky.samplewebsocket.websocket;
 
import cn.zifangsky.samplewebsocket.service.EchoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
 
import javax.annotation.Resource;
import java.text.MessageFormat;
 
/**
 * 通过继承 {@link org.springframework.web.socket.handler.AbstractWebSocketHandler} 的示例
 *
 * @author zifangsky
 * @date 2018/10/9
 * @since 1.0.0
 */
public class EchoWebSocketHandler extends TextWebSocketHandler{
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    @Resource(name = "echoServiceImpl")
    private EchoService echoService;
 
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("Opened new session in instance " + this);
    }
 
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //组装返回的Echo信息
        String echoMessage = this.echoService.echo(message.getPayload());
        logger.debug(MessageFormat.format("Echo message \"{0}\"", echoMessage));
 
        session.sendMessage(new TextMessage(echoMessage));
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.close(CloseStatus.SERVER_ERROR);
        logger.debug("Info: WebSocket connection closed.");
    }
}

(2) WebSocket related configuration:

import cn.zifangsky.samplewebsocket.websocket.EchoWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
/**
 * WebSocket相关配置
 *
 * @author zifangsky
 * @date 2018/9/30
 * @since 1.0.0
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
 
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(echoWebSocketHandler(), "/echoMessage");
        registry.addHandler(echoWebSocketHandler(), "/echoMessage_SockJS").withSockJS();
    }
 
    /**
     * 通过继承 {@link org.springframework.web.socket.handler.AbstractWebSocketHandler} 的示例
     */
    @Bean
    public WebSocketHandler echoWebSocketHandler(){
        return new EchoWebSocketHandler();
    }
 
}

As can be seen from the above code, in addition to configuring the basic WebSocket (that is, the connection address of /echoMessage), SockJS is also used to configure an alternative when the browser does not support WebSocket technology (that is, the connection address of /echoMessage_SockJS).
(3) Two sample pages:
i) echo.html:

<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>WebSocket Examples: Reverse</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }
 
        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
 
        .layui-btn {
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        var ws = null;
 
        $(function () {
            var target = $("#target");
            if (window.location.protocol === 'http:') {
                target.val('ws://' + window.location.host + target.val());
            } else {
                target.val('wss://' + window.location.host + target.val());
            }
        });
 
        function setConnected(connected) {
            var connect = $("#connect");
            var disconnect = $("#disconnect");
            var echo = $("#echo");
 
            if (connected) {
                connect.addClass("layui-btn-disabled");
                disconnect.removeClass("layui-btn-disabled");
                echo.removeClass("layui-btn-disabled");
            } else {
                connect.removeClass("layui-btn-disabled");
                disconnect.addClass("layui-btn-disabled");
                echo.addClass("layui-btn-disabled");
            }
 
            connect.attr("disabled", connected);
            disconnect.attr("disabled", !connected);
            echo.attr("disabled", !connected);
        }
 
        //连接
        function connect() {
            var target = $("#target").val();
 
            ws = new WebSocket(target);
            ws.onopen = function () {
                setConnected(true);
                log('Info: WebSocket connection opened.');
            };
            ws.onmessage = function (event) {
                log('Received: ' + event.data);
            };
            ws.onclose = function () {
                setConnected(false);
                log('Info: WebSocket connection closed.');
            };
        }
 
        //断开连接
        function disconnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
            setConnected(false);
        }
 
        //Echo
        function echo() {
            if (ws != null) {
                var message = $("#message").val();
                log('Sent: ' + message);
                ws.send(message);
            } else {
                alert('WebSocket connection not established, please connect.');
            }
        }
 
        //日志输出
        function log(message) {
            console.debug(message);
        }
    </script>
</head>
<body>
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
        enabled. Please enable
        Javascript and reload this page!</h2></noscript>
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>Echo</legend>
            <div>
                <input id="target" type="text" class="layui-input" size="40" style="width: 350px" value="/echoMessage"/>
            </div>
            <div>
                <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
                <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="disconnect();">Disconnect
                </button>
 
            </div>
            <div>
                <textarea id="message" class="layui-textarea" placeholder="请输入请求的内容" style="width: 350px"></textarea>
            </div>
            <div>
                <button id="echo" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="echo();">Echo message
                </button>
            </div>
        </div>
    </div>
</body>
</html>
ii)echo_sockjs.html:
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>WebSocket Examples: Reverse</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }
 
        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
 
        .layui-btn {
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        var ws = null;
 
        $(function () {
            var target = $("#target");
            if (window.location.protocol === 'http:') {
                target.val('http://' + window.location.host + target.val());
            } else {
                target.val('https://' + window.location.host + target.val());
            }
        });
 
        function setConnected(connected) {
            var connect = $("#connect");
            var disconnect = $("#disconnect");
            var echo = $("#echo");
 
            if (connected) {
                connect.addClass("layui-btn-disabled");
                disconnect.removeClass("layui-btn-disabled");
                echo.removeClass("layui-btn-disabled");
            } else {
                connect.removeClass("layui-btn-disabled");
                disconnect.addClass("layui-btn-disabled");
                echo.addClass("layui-btn-disabled");
            }
 
            connect.attr("disabled", connected);
            disconnect.attr("disabled", !connected);
            echo.attr("disabled", !connected);
        }
 
        //连接
        function connect() {
            var target = $("#target").val();
 
            ws = new SockJS(target);
            ws.onopen = function () {
                setConnected(true);
                log('Info: WebSocket connection opened.');
            };
            ws.onmessage = function (event) {
                log('Received: ' + event.data);
            };
            ws.onclose = function () {
                setConnected(false);
                log('Info: WebSocket connection closed.');
            };
        }
 
        //断开连接
        function disconnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
            setConnected(false);
        }
 
        //Echo
        function echo() {
            if (ws != null) {
                var message = $("#message").val();
                log('Sent: ' + message);
                ws.send(message);
            } else {
                alert('WebSocket connection not established, please connect.');
            }
        }
 
        //日志输出
        function log(message) {
            console.debug(message);
        }
    </script>
</head>
<body>
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
        enabled. Please enable
        Javascript and reload this page!</h2></noscript>
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>Echo With SockJS</legend>
            <div>
                <input id="target" type="text" class="layui-input" size="40" style="width: 350px" value="/echoMessage_SockJS"/>
            </div>
            <div>
                <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
                <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="disconnect();">Disconnect
                </button>
 
            </div>
            <div>
                <textarea id="message" class="layui-textarea" placeholder="请输入请求的内容" style="width: 350px"></textarea>
            </div>
            <div>
                <button id="echo" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="echo();">Echo message
                </button>
            </div>
        </div>
    </div>
</body>
</html>

The specific effect is omitted, and you can run the source code to view it by yourself.

Use STOMP message to achieve

The so-called STOMP (Simple Text Oriented Messaging Protocol) is to provide a frame-based wire format layer on the basis of WebSocket. It defines a set of standardized formats for sending simple text messages (STOMP messages are based on Text, and of course also supports the transmission of binary data). At present, many server-side message queues already support STOMP, such as RabbitMQ, ActiveMQ, etc.
(1) WebSocket related configuration:

import cn.zifangsky.stompwebsocket.interceptor.websocket.MyChannelInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
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;
 
/**
 * WebSocket相关配置
 *
 * @author zifangsky
 * @date 2018/9/30
 * @since 1.0.0
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
    @Autowired
    private MyChannelInterceptor myChannelInterceptor;
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp-websocket").withSockJS();
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //客户端需要把消息发送到/message/xxx地址
        registry.setApplicationDestinationPrefixes("/message");
        //服务端广播消息的路径前缀,客户端需要相应订阅/topic/yyy这个地址的消息
        registry.enableSimpleBroker("/topic");
    }
 
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(myChannelInterceptor);
    }
 
}

As can be seen from the above code, there are several addresses set up here. A brief explanation is as follows:
• First, an endpoint named /stomp-websocket is registered, which is the address where the STOMP client connects.
• In addition, it is defined that the server-side processing WebSocket message prefix is ​​/message, this address is used by the client to send messages to the server (for example, the client sends a message to the address /message/hello, then the server uses @MessageMapping("/ hello”) This annotation is used to receive and process messages)
• Finally, a simple message agent is defined, which is the path prefix of the server broadcast message (for example, the client listens to the address /topic/greeting, then the server can use @SendTo ("/Topic/greeting") This annotation sends a STOMP message to the client).
It should be noted that an interceptor named MyChannelInterceptor is also added to the above code, the purpose is to print a log after the client disconnects. The relevant code is as follows:
As can be seen from the above code, there are several addresses set here, and a brief explanation is as follows:
• First, an endpoint named /stomp-websocket is registered, which is the address where the STOMP client connects.
• In addition, it is defined that the server-side processing WebSocket message prefix is ​​/message, this address is used by the client to send messages to the server (for example, the client sends a message to the address /message/hello, then the server uses @MessageMapping("/ hello”) This annotation is used to receive and process messages)
• Finally, a simple message agent is defined, which is the path prefix of the server broadcast message (for example, the client listens to the address /topic/greeting, then the server can use @SendTo ("/Topic/greeting") This annotation sends a STOMP message to the client).

package cn.zifangsky.stompwebsocket.interceptor.websocket;
 
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.stereotype.Component;
 
import java.security.Principal;
import java.text.MessageFormat;
 
/**
 * 自定义{@link org.springframework.messaging.support.ChannelInterceptor},实现断开连接的处理
 *
 * @author zifangsky
 * @date 2018/10/10
 * @since 1.0.0
 */
@Component
public class MyChannelInterceptor implements ChannelInterceptor{
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        StompCommand command = accessor.getCommand();
 
        //用户已经断开连接
        if(StompCommand.DISCONNECT.equals(command)){
            String user = "";
            Principal principal = accessor.getUser();
            if(principal != null && StringUtils.isNoneBlank(principal.getName())){
                user = principal.getName();
            }else{
                user = accessor.getSessionId();
            }
 
            logger.debug(MessageFormat.format("用户{0}的WebSocket连接已经断开", user));
        }
    }
 
}

(2) Use @MessageMapping and @SendTo annotations to process messages:
@MessageMapping annotations are used to monitor client messages of a specified path, while @SendTo annotations are used to send messages from the server to the client that monitors the path.

package cn.zifangsky.stompwebsocket.controller;
 
import cn.zifangsky.stompwebsocket.model.websocket.Greeting;
import cn.zifangsky.stompwebsocket.model.websocket.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
 
/**
 * Greeting
 * @author zifangsky
 * @date 2018/9/30
 * @since 1.0.0
 */
@Controller
public class GreetingController {
 
    @MessageMapping("/hello")
    @SendTo("/topic/greeting")
    public HelloMessage greeting(Greeting greeting) {
        return new HelloMessage("Hello," + greeting.getName() + "!");
    }
}

(3) Sample page:

<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>WebSocket Examples: Reverse</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }
        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
        .layui-btn {
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        var stompClient = null;
        $(function () {
            var target = $("#target");
            if (window.location.protocol === 'http:') {
                target.val('http://' + window.location.host + target.val());
            } else {
                target.val('https://' + window.location.host + target.val());
            }
        });
        function setConnected(connected) {
            var connect = $("#connect");
            var disconnect = $("#disconnect");
            var echo = $("#echo");
            if (connected) {
                connect.addClass("layui-btn-disabled");
                disconnect.removeClass("layui-btn-disabled");
                echo.removeClass("layui-btn-disabled");
            } else {
                connect.removeClass("layui-btn-disabled");
                disconnect.addClass("layui-btn-disabled");
                echo.addClass("layui-btn-disabled");
            }
            connect.attr("disabled", connected);
            disconnect.attr("disabled", !connected);
            echo.attr("disabled", !connected);
        }
        //连接
        function connect() {
            var target = $("#target").val();
            var ws = new SockJS(target);
            stompClient = Stomp.over(ws);
            stompClient.connect({}, function () {
                setConnected(true);
                log('Info: STOMP connection opened.');
                //订阅服务端的/topic/greeting地址
                stompClient.subscribe("/topic/greeting", function (greeting) {
                    log('Received: ' + JSON.parse(greeting.body).content);
                })
            },function () {
                //断开处理
                setConnected(false);
                log('Info: STOMP connection closed.');
            });
        }
        //断开连接
        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
                stompClient = null;
            }
            setConnected(false);
            log('Info: STOMP connection closed.');
        }
        //向服务端发送姓名
        function sendName() {
            if (stompClient != null) {
                var username = $("#username").val();
                log('Sent: ' + username);
                stompClient.send("/message/hello", {}, JSON.stringify({'name': username}));
            } else {
                alert('STOMP connection not established, please connect.');
            }
        }
        //日志输出
        function log(message) {
            console.debug(message);
        }
    </script>
</head>
<body>
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
        enabled. Please enable
        Javascript and reload this page!</h2></noscript>
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>STOMP Message With SockJS</legend>
            <div>
                <input id="target" type="text" class="layui-input" size="40" style="width: 350px" value="/stomp-websocket"/>
            </div>
            <div>
                <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
                <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="disconnect();">Disconnect
                </button>
            </div>
            <div>
                <input id="username" type="text" class="layui-input" size="40" style="width: 350px" placeholder="请输入你的姓名" value=""/>
            </div>
            <div>
                <button id="echo" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="sendName();">Say hello
                </button>
            </div>
        </div>
    </div>
</body>
</html>

Guess you like

Origin blog.csdn.net/qq_17010193/article/details/114391336