Spring Boot WebSocket

簡介:WebSocket協議是基於TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通訊——容許服務器主動發送信息給客戶端。javascript

Config:html

Controller:java


 

完整代碼以下:jquery

Html:web

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot WebSocket</title>

</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">瀏覽器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">鏈接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">斷開鏈接</button>
    </div>
    <div id="conversationDiv">
        <label>輸入你的名字</label><input type="text" id="msg" />
        <button id="sendName" onclick="sendMsg();">發送</button>
        <p id="response"></p>
    </div>
</div>
<script src="/js/jquery-2.1.0.min.js"></script>
<script src="/js/stomp.min.js"></script>
<script src="/js/sockjs-0.3.4.min.js"></script>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }

    function connect() {
        var socket = new SockJS('/ruan');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('開始進行鏈接Connected: ' + frame);
            stompClient.subscribe('/resp', function(respnose){
                showResponse(respnose.body);
            });
        });
    }


    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendMsg() {
        var msg = $('#msg').val();
        stompClient.send("/msg", {}, msg);//5
    }

    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }
</script>
</body>
</html>

 Config:spring

package com.example.websocketdemo.config;

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;

/**
 * @author Ruan
 * @date 2018/4/11 21:13
 * @EnableWebSocketMessageBroker 開啓使用STOMP協議來傳輸基於代理(MessageBroker)的消息,
 * 讓controller支持@MessageMapping註解,和requestMapping相似
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //註冊Stomp節點,並使用SockJS協議
        registry.addEndpoint("/ruan").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //用來定義返回的規範.返回url以 /resp 開始
        registry.enableSimpleBroker("/resp");
    }
}

 Contoller:api

package com.example.websocketdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

/**
 * @author Ruan
 * @date 2018/4/11 21:15
 */
@Controller
@Slf4j
public class WsController {
    /**
     * 接收來自瀏覽器經過/msg 這個api發送過來的消息
     * @MessageMapping 瀏覽器經過這個註解裏面的api訪問改方法
     * @SendTo 返回給瀏覽器的地址
     * @param msg 消息內容
     * @return
     */
    @MessageMapping("/msg")
    @SendTo("/resp")
    public String receive(String msg) {
        StringBuilder sbReceiver = new StringBuilder("服務器返回消息: ");
        sbReceiver.append(msg);
        log.info(sbReceiver.toString());
        return sbReceiver.toString();
    }
}
相關文章
相關標籤/搜索