websocket+stomp子協議 實現資料互通
第一次寫部落格,也該學學沒事寫寫部落格啦 這幾天在學習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 實現簡單的訂閱廣播訊息和訂閱個人訊息
相關文章
- 使用ensp搭建路由拓撲,並使用isis協議實現網路互通實操路由協議
- 使用ensp搭建路由拓撲,並使用ospf協議實現網路互通實操路由協議
- 實現 Raft 協議Raft協議
- Java入門:UDP協議傳送/接收資料實現JavaUDP協議
- Java入門:TCP協議傳送/接收資料實現JavaTCP協議
- 一攬子協議協議
- HTTP協議資料包HTTP協議
- TCP協議資料格式TCP協議
- RSA加密解密(無資料大小限制,php、go、java互通實現)加密解密PHPGoJava
- Java基礎 UDP協議下,收發資料的程式碼實現JavaUDP協議
- 實現網站由http協議轉為https協議網站HTTP協議
- PPM協議的輸出實現協議
- PDP分組資料協議協議
- STOMP協議——基於Websocket實現協議Web
- 使用生成器 --實現迭代協議協議
- 教你用Perl實現Smgp協議協議
- FFmpeg實現監控攝像頭的RTSP協議轉RTMP協議直播協議
- Cisco發現協議協議
- Go語言實現HTTPS加密協議GoHTTP加密協議
- QQ 快速登入協議分析與實現協議
- 使用netty實現socks5協議Netty協議
- 利用飛鴿協議實現通訊功能協議
- RPC框架實現 - 通訊協議篇RPC框架協議
- 教你如何使用Zig實現Cmpp協議協議
- 通訊協議protobuf的原理與實現協議
- 配置RIP、OSPF實現全網互通
- 詳解通訊資料協議ProtoBuf協議
- 【網路協議】資料鏈路層協議
- 實用TCP協議(1):TCP 協議簡介TCP協議
- 網路協議之:基於UDP的高速資料傳輸協議UDT協議UDP
- SMTP協議解讀以及如何使用SMTP協議傳送電子郵件協議
- 協議轉換閘道器如何實現更多裝置聯網和資料採集協議
- 無線模組透過TCP/IP協議實現與PC端的資料傳輸解析TCP協議
- 造輪子系列(二): 史上最簡單的長連線通訊協議及實現協議
- MQTT協議實踐MQQT協議
- 老司機帶你用 PHP 實現 Websocket 協議PHPWeb協議
- 原生JS實現移動端線上籤協議JS協議
- quinn-rs/quinn: QUIC協議的Rust實現UI協議Rust