<!DOCTYPE html>
<html>

<head>
    <title>stomp</title>
</head>

<body>
    Welcome<br/><input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <button onclick="subscribe1()">订阅消息/topic/device</button>
    <hr/>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    <div id="message"></div>
</body>

<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script type="text/javascript">
    // 建立连接对象（还未发起连接）
    var socket = new SockJS("http://192.168.0.100:8080/webSocketServer");

    // 获取 STOMP 子协议的客户端对象
    var stompClient = Stomp.over(socket);

    // 向服务器发起websocket连接并发送CONNECT帧
    stompClient.connect(
        {},
        function connectCallback(frame) {
            // 连接成功时（服务器响应 CONNECTED 帧）的回调方法
            setMessageInnerHTML("连接成功");
        },
        function errorCallBack(error) {
            // 连接失败时（服务器响应 ERROR 帧）的回调方法
            setMessageInnerHTML("连接失败");
        }
    );

    //订阅消息
    function subscribe1() {
        stompClient.subscribe('/topic/device', function (response) {
            setMessageInnerHTML("已成功订阅/topic/device");
            var returnData = JSON.parse(response.body);
            setMessageInnerHTML("/topic/device 你接收到的消息为:" + returnData.responseMessage);
        });
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

</script>

</html>