1. 程式人生 > >Spring WebSocket 初探

Spring WebSocket 初探

public class Greeting {
    private String content;

    public Greeting(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}
public class HelloMessage {
    private String name;

    public String getName() {
        return name;
    }
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //啟用 STOMP 代理中繼功能: 並將其目的地字首設定為 "/topic" or "/greetings" ;
        // spring就能知道 所有目的地字首為 "/topic" or "/greetings" 的訊息都會發送到 STOMP 代理中;
        config.enableSimpleBroker("/topic", "/greetings");

        //設定應用的字首為 "app":所有目的地以 "/app" 打頭的訊息(傳送訊息url not 連線url)都會路由到 帶有 @MessageMapping 註解的方法中,而不會發布到 代理佇列中;
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/hello").withSockJS();
        // 在網頁上我們就可以通過這個連結 /server/hello 來和伺服器的WebSocket連線
    }
}
@Controller
public class GreetingController {

    // @MessageMapping defines the sending addr for client.
    // 訊息傳送地址: /app/hello
    @MessageMapping("/hello")
    @SendTo("/topic")
    public Greeting greeting(HelloMessage message) throws Exception {
        System.out.println("receiving " + message.getName());
        System.out.println("connecting successfully.");
        return new Greeting("Hello, " + message.getName() + "!");
    }

    @SubscribeMapping("/macro")
    public Greeting handleSubscription() {
        Greeting greeting = new Greeting("SubscribeMapping macro");
        return greeting;
    }

    private SimpMessageSendingOperations  template;

    @Autowired
    public GreetingController(SimpMessageSendingOperations  template) {
        this.template = template;
    }

    @RequestMapping(path="/send")
    @ResponseBody
    public String send(@RequestParam String message) {
        //傳送訊息
        this.template.convertAndSend("/topic", new Greeting(message));
        return "done";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path ;
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Websocket</title>

    <script src="<%=basePath%>/resources/js/jquery-2.1.4.min.js"></script>
    <!--引入sockjs-->
    <script src="<%=basePath%>/resources/js/sockjs-1.1.1.js"></script>
    <script src="<%=basePath%>/resources/js/stomp.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 檔案 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <script type="text/javascript">

        var stompClient = null;

        //this line.
        function connect() {
            var socket = new SockJS("<%=basePath%>/hello");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                stompClient.subscribe('/topic', function(greeting){
                    log("Received:"+JSON.parse(greeting.body).content);
                });

                stompClient.subscribe('/app/macro',function(greeting){
                    log("Received:"+JSON.parse(greeting.body).content);
                });
            });
        }

        function sendMsg() {
            stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#message").val()}));
            log("send:name="+$("#message").val());
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
        }

        function log(message) {
            var html = '<p style="word-wrap: break-word;">'+message+'</p>';
            $("#console").append(html);
        }
    </script>
</head>
<body>

<div>
    <div id="connect-container" style="text-align: center;margin: 40px;">
        <div>
            <button id="connect" onclick="connect();">連線</button>
            <button id="disconnect" style="display: none" onclick="disconnect()">關閉連線</button>
            <input id="message" style="width: 300px" placeholder="輸入訊息內容"/>
            <button onclick="sendMsg();">傳送訊息</button>
        </div>
        <div id="console-container">
            <div id="console"></div>
        </div>
    </div>
</div>
</body>
</html>