websocket+stomp子協議 實現資料互通

yahweh_liu發表於2018-03-28

第一次寫部落格,也該學學沒事寫寫部落格啦   這幾天在學習websocket協議,具體原理什麼的請百度百科,為了節省篇幅,我直接貼出自己整合的demo,網上也看了好多部落格,大牛的文章,幾番周折可用,中間也遇到一些問題,,


pom.xml

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.yahweh</groupId>
	<artifactId>springmvc_websocket</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>


	  <properties>
        <spring.version>4.2.8.RELEASE</spring.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        
        
        <dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.3.0</version>
		</dependency>
        
        
    </dependencies>
	<build>
		<plugins>
			<!-- 編碼和編譯和JDK版本 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>utf8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>



Message.java

package cn.yahweh.bean;

/**
 * 
 * 瀏覽器向伺服器傳送的訊息使用此類接受
 */
public class Message {
    private String name;

    public String getName(){
        return name;
    }
}

Response.java

package cn.yahweh.bean;

/**
 * 
 * 伺服器向瀏覽器傳送的此類訊息。
 */
public class Response {
    public void setResponseMessage(String responseMessage) {
        this.responseMessage = responseMessage;
    }

    private String responseMessage;
    public Response(String responseMessage){
        this.responseMessage = responseMessage;
    }
    public String getResponseMessage(){
        return responseMessage;
    }
}

websocket配置類

package cn.yahweh.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

/**
 * 
 */
@Configuration
@EnableWebSocketMessageBroker
//通過EnableWebSocketMessageBroker 開啟使用STOMP協議來傳輸基於代理(message broker)的訊息,此時瀏覽器支援使用@MessageMapping 就像支援@RequestMapping一樣。
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{


    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) { //endPoint 註冊協議節點,並對映指定的URl

        //註冊一個Stomp 協議的endpoint,並指定 SockJS協議
        registry.addEndpoint("/hello").setAllowedOrigins("*").withSockJS();
           
       
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {//配置訊息代理(message broker)
        //廣播式應配置一個/topic 訊息代理
        registry.enableSimpleBroker("/topic");

        //點對點式增加一個/queue 訊息代理
        registry.enableSimpleBroker("/queue","/topic");

    }
}

controller層
package cn.yahweh.controller;




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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.yahweh.bean.Message;
import cn.yahweh.bean.Response;



/**
 * 
 *
 */

@Controller
public class WebSocketController {
   
    @Autowired
    private SimpMessagingTemplate messagingTemplate;


   
    @RequestMapping(value = "/sign")
    public String sign(){
        return  "sign";
    }
    
    
    
    @MessageMapping("/signed")
    @SendTo(value="/topic/signed")
    public Response handleSign(Message message){
    	
    	System.out.println(message.getName());
    	
		return new Response( message.getName() + "簽到成功!");
    	
    	
    	
    	
    }
    
}

springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

	<!-- 開啟驅動 -->
	<mvc:annotation-driven />

	<!-- 註解掃描 -->
	<context:component-scan base-package="cn.yahweh" />

	<!-- 開啟註解開發 -->
	<context:annotation-config />


	<!-- 對靜態資源放行 -->
	<mvc:default-servlet-handler />
	
	
	<bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/view/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean> 

</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance  http://www.springmodules.org/schema/cache/springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd       
     "> 
  <display-name>springmvc_websocket</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  

    
    <!-- Spring MVC -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
       
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

  
</web-app>

這裡需要注意的是,我使用的是本地js 如果需要請自行下載更換,想快速看效果的小夥伴可以使用線上js
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
    <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

請自行更換

 sign.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta charset="UTF-8" />
<head>
<title>Home</title>

	<script type="text/javascript" src="js/jquery.js" ></script>
    <script type="text/javascript" src="js/stomp.min.js"></script>
    <script type="text/javascript" src="js/sockjs.min.js"></script>

</head>
<body>


	<script type="text/javascript">


   
    var socket = new SockJS('/springmvc_websocket/hello'); //連結SockJS 的endpoint 名稱為"/endpointWisely"
        var stompClient = Stomp.over(socket);//使用stomp子協議的WebSocket 客戶端
          stompClient.connect({}, function(frame) {//連結Web Socket的服務端。
        
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/signed', function(respnose){ //訂閱/topic/getResponse 目標傳送的訊息。這個是在控制器的@SendTo中定義的。
							alert(JSON.parse(respnose.body).responseMessage);
    });
});
   
   
   
        
function sendSign() {
    var name = $('#name').val();
		//通過stompClient.send 向/welcome 目標 傳送訊息,這個是在控制器的@messageMapping 中定義的。
    stompClient.send("/signed", {}, JSON.stringify({ 'name': name }));
}
   
</script>

	<div id="output">
		<input type="text" id="name" />
		<button id="sendName" onclick="sendSign();">簽到</button>


	</div>

</body>
</html>


以下是自己學習的相關文章

https://blog.csdn.net/jqsad/article/details/77745379   客戶端api

https://www.cnblogs.com/jianwei-dai/p/6273505.html  例項

https://www.cnblogs.com/sally-zhou/p/5658648.html   websocket 原理

https://blog.csdn.net/u013929107/article/details/49904999  入門案例

https://www.jianshu.com/p/f0cbfc1f0a50   spring+websocket  訊息互動

https://www.cnblogs.com/caer/p/6105884.html spring+websocket 整合

https://blog.csdn.net/gisredevelopment/article/details/38392629/  spring+websocket+springMVC 整合

https://blog.csdn.net/yingxiake/article/details/51224929 spring websocket 基於編碼的方式手動進行推送

https://blog.csdn.net/yingxiake/article/details/51224569 spring websocket 使用@SendToUser

https://blog.csdn.net/u013627689/article/details/73611945 spring+stomp+webSocket+SockJS 實現簡單的訂閱廣播訊息和訂閱個人訊息

 


相關文章