springboot + websocket + spring-messaging實現服務器向瀏覽器廣播式

目錄結構javascript

 pom.xmlhtml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.web.socket</groupId>
    <artifactId>websocket</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>websocket Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>2.0.0.RELEASE</version>  
    </parent>  
    <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <java.version>1.8</java.version>  
    </properties> 
    <dependencies>
         <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-messaging</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter</artifactId>  
        </dependency>  
        <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>javax.servlet</groupId>  
            <artifactId>javax.servlet-api</artifactId>  
            <scope>provided</scope>  
        </dependency> 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>websocket</finalName>
    </build>
</project>

 WebSocketConfig.javajava

package com.web.socket.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
 
@Configuration
//表示開啓使用STOMP協議來傳輸基於代理的消息,Broker就是代理的意思。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker(AppConfig.BROKER);
	}
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//這一行代碼用來註冊STOMP協議節點,同時指定使用SockJS協議。 
		registry.addEndpoint(AppConfig.ENDPOINT).withSockJS();
	}
}

 AppConfig.javajquery

package com.web.socket.config;

public class AppConfig {
	/**
	 * 被訂閱的頻道
	 */
	public static final String SUBSCRIBE = "/topic/message";
	/**
	 * stomp節點
	 */
	public static final String ENDPOINT = "/endpointYC";
	/**
	 * 消息代理
	 */
	public static final String BROKER = "/topic";
}

 WebSocketController.javaweb

package com.web.socket.controller;
 
 
import java.io.IOException;
 
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.web.socket.config.AppConfig;
import com.web.socket.entity.RequestMessage;
import com.web.socket.entity.ResponseMessage;
 
@Controller
public class WsController {
	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;
	
	/**
	 * @title websocket產生消息,並推送
	 * @param message
	 * @return
	 */
	@MessageMapping("/ws")//和@RequestMapping相似
        @SendTo(AppConfig.SUBSCRIBE)//當服務器有消息須要推送的時候,會對訂閱了@SendTo中路徑的瀏覽器發送消息
        public ResponseMessage say(RequestMessage message) {
            System.out.println(message.getName());
            return new ResponseMessage(message.toString());
        }
	
	/**
	 * @title http請求產生消息,並推送
	 * @param message
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/http")
	@ResponseBody
	public String send(@RequestBody RequestMessage message) throws IOException {
		System.out.println(message.getName());
		simpMessagingTemplate.convertAndSend(AppConfig.SUBSCRIBE,new ResponseMessage(message.toString()) );
		return "success";
	}
}

 ws.htmlspring

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>廣播式WebSocket</title>
    <script th:src="@{static/js/sockjs.min.js}"></script>
    <script th:src="@{static/js/stomp.js}"></script>
    <script th:src="@{static/js/jquery-3.3.1.min.js}"></script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #e80b0a;">Sorry,瀏覽器不支持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="name"/>
        <label>內容</label><input type="text" id="content"/>
        <button id="sendName" onclick="sendName();">發送</button>
        <p id="response"></p>
    </div>
</div>
<script type="text/javascript">
    var stompClient = null;
    /**
     * 設置組件樣式
     * @param {Object} connected
     */
    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }
    /**
     * 建立socket鏈接
     */
    function connect() {
    	//連接SockJS 的endpoint 名稱爲endpointSang
        var socket = new SockJS('/endpointYC');
        //使用stomp子協議的WebSocket 客戶端
        stompClient = Stomp.over(socket);
        //連接Web Socket的服務端。
        stompClient.connect({}, function (frame) {
            setConnected(true);
            //訂閱/topic/message頻道,並對收到信息進行處理
            stompClient.subscribe('/topic/message', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            })
        });
    }
    /**
     * 斷開鏈接
     */
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
    }
    /**
     * 向服務器發送消息
     */
    function sendName() {
        var name = $('#name').val();
        var content = $('#content').val();
        stompClient.send("/ws", {}, JSON.stringify({'name': name,'content':content,'date':new Date()}));
    }
    /**
     * 替換文本
     * @param {Object} message 服務器返回數據
     */
    function showResponse(message) {
        $("#response").html(message);
    }
</script>
</body>
</html>

 

使用瀏覽器訪http://127.0.0.1/ws就能夠測試websocket方式廣播。apache

在有socket鏈接的狀況下,訪問http://127.0.0.1/http,並使用post方式請求,就能夠在ws頁面看到發送的數據了。api

相關文章
相關標籤/搜索