使用spring的websocket創(chuàng)建通信服務(wù)的示例代碼
基于socket通信,spring
也有自己的socket通信服務(wù):websocket
,這次就介紹如何在spring項(xiàng)目中使用websocket
進(jìn)行通信交互。
后臺(tái):spring boot;前臺(tái):angularjs
后臺(tái)建立服務(wù)
首先我們先建立起后臺(tái)的服務(wù),以實(shí)現(xiàn)進(jìn)行socket連接。
1.引入websocket依賴
建立好一個(gè)maven項(xiàng)目之后,我們需要在xml
中引入websocket
的相關(guān) 依賴:
<dependencies> <!--webSocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.0</version> </dependency> </dependencies>
2.配置類
引入依賴后,就需要我們進(jìn)行配置類的編寫:
public class WebSocketConfig {}
這個(gè)類需要實(shí)現(xiàn)一個(gè)接口,來幫助我們進(jìn)行socket
的連接,并接受發(fā)送過來的消息。比如下面這樣:
package com.mengyunzhi.SpringMvcStudy.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; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/server"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { //注冊(cè)STOMP協(xié)議節(jié)點(diǎn),同時(shí)指定使用SockJS協(xié)議 registry .addEndpoint("/websocket-server") .setAllowedOrigins("*") .withSockJS(); } }
通常的配置我就不在這里解釋了,值得一提的是,我們使用了@EnableWebSocketMessageBroker
這個(gè)注解,從字面上我們不難猜出,它表示支持websocket
提供的消息代理。
然后我們實(shí)現(xiàn)configureMessageBroker()
方法,來配置消息代理。在這個(gè)方法中,我們先調(diào)用enableSimpleBroker()
來創(chuàng)建一個(gè)基于內(nèi)存的消息代理,他表示以/topic
為前綴的消息將發(fā)送回客戶端。接著設(shè)置一個(gè)請(qǐng)求路由前綴,它綁定了@MessageMapping
(這個(gè)后面會(huì)用到)注解,表示以/server
為前綴的消息,會(huì)發(fā)送到服務(wù)器端。
最后實(shí)現(xiàn)了registerStompEndpoints()
方法,用來注冊(cè)/websocket-server
端點(diǎn)來建立服務(wù)器。
3.控制器
這時(shí)我們要建立一個(gè)供前臺(tái)訪問的接口來發(fā)送消息。
@MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(1000); // simulated delay return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!"); }
其中@MessageMapping
注解就是我們前面提到的,前臺(tái)會(huì)將消息發(fā)送到/server/hello
這里。
然后還有一個(gè)@SendTo
注解,它表示服務(wù)器返回給前臺(tái)的消息,會(huì)發(fā)送到/topic/greeting
這里。
前臺(tái)客戶端
服務(wù)器部分建立好后,接著我們就要去建立客戶端部分
1.客戶端界面
<!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> <link href="/main.css" rel="external nofollow" rel="stylesheet"> <script src="/webjars/jquery/jquery.min.js"></script> <script src="/webjars/sockjs-client/sockjs.min.js"></script> <script src="/webjars/stomp-websocket/stomp.min.js"></script> <script src="/app.js"></script> </head> <body> <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable Javascript and reload this page!</h2></noscript> <div id="main-content" class="container"> <div class="row"> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="connect">WebSocket connection:</label> <button id="connect" class="btn btn-default" type="submit">Connect</button> <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect </button> </div> </form> </div> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="name">What is your name?</label> <input type="text" id="name" class="form-control" placeholder="Your name here..."> </div> <button id="send" class="btn btn-default" type="submit">Send</button> </form> </div> </div> <div class="row"> <div class="col-md-12"> <table id="conversation" class="table table-striped"> <thead> <tr> <th>Greetings</th> </tr> </thead> <tbody id="greetings"> </tbody> </table> </div> </div> </div> </body> </html>
這部分沒什么說的,主要就是其中引的連個(gè)js文件:
<script src="/webjars/sockjs-client/sockjs.min.js"></script> <script src="/webjars/stomp-websocket/stomp.min.js"></script>
這兩個(gè)文件幫助我們利用sockjs
和stomp
實(shí)現(xiàn)客戶端。
創(chuàng)建邏輯
var stompClient = null; function setConnected(connected) { $("#connect").prop("disabled", connected); $("#disconnect").prop("disabled", !connected); if (connected) { $("#conversation").show(); } else { $("#conversation").hide(); } $("#greetings").html(""); } function connect() { var socket = new SockJS('/websocket-server'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings', function (greeting) { showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } function sendName() { stompClient.send("/server/hello", {}, JSON.stringify({'name': $("#name").val()})); } function showGreeting(message) { $("#greetings").append("<tr><td>" + message + "</td></tr>"); } $(function () { $("form").on('submit', function (e) { e.preventDefault(); }); $( "#connect" ).click(function() { connect(); }); $( "#disconnect" ).click(function() { disconnect(); }); $( "#send" ).click(function() { sendName(); }); });
這個(gè)文件主要注意connect()
和sendName()
這兩個(gè)方法。
最后實(shí)現(xiàn)的效果如下:
官方文檔:
https://spring.io/guides/gs/messaging-stomp-websocket/
https://docs.spring.io/spring/docs/4.3.20.RELEASE/spring-framework-reference/htmlsingle/#websocket
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- PHP實(shí)現(xiàn)websocket通信的方法示例
- WebSocket的通信過程與實(shí)現(xiàn)方法詳解
- android利用websocket協(xié)議與服務(wù)器通信
- C# websocket及時(shí)通信協(xié)議的實(shí)現(xiàn)方法示例
- 使用 Spring Boot 實(shí)現(xiàn) WebSocket實(shí)時(shí)通信
- Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)
- .NET實(shí)現(xiàn)WebSocket服務(wù)端即時(shí)通信實(shí)例
- WebSocket+node.js創(chuàng)建即時(shí)通信的Web聊天服務(wù)器
- Python通過websocket與js客戶端通信示例分析
- 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解
相關(guān)文章
JAVA實(shí)現(xiàn) SpringMVC方式的微信接入、實(shí)現(xiàn)簡(jiǎn)單的自動(dòng)回復(fù)功能
這篇文章主要介紹了JAVA實(shí)現(xiàn) SpringMVC方式的微信接入、實(shí)現(xiàn)簡(jiǎn)單的自動(dòng)回復(fù)功能的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11spring aop實(shí)現(xiàn)用戶權(quán)限管理的示例
本篇文章主要介紹了spring aop實(shí)現(xiàn)用戶權(quán)限管理的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12Java調(diào)用wsdl接口的兩種方法(axis和wsimport)
本文主要介紹了Java調(diào)用wsdl接口的兩種方法(axis和wsimport),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03IntelliJ?IDEA教程之clean或者install?Maven項(xiàng)目的操作方法
這篇文章主要介紹了IntelliJ?IDEA教程之clean或者install?Maven項(xiàng)目的操作方法,本文分步驟給大家介紹兩種方式講解如何調(diào)試出窗口,需要的朋友可以參考下2023-04-04Spring Boot非Web項(xiàng)目運(yùn)行的方法
這篇文章主要給大家介紹了關(guān)于Spring Boot非Web項(xiàng)目運(yùn)行的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09高并發(fā)下如何避免重復(fù)數(shù)據(jù)產(chǎn)生技巧
這篇文章主要為大家介紹了高并發(fā)下如何避免重復(fù)數(shù)據(jù)的產(chǎn)生技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07idea創(chuàng)建的idea項(xiàng)目時(shí)springframework出現(xiàn)紅色的原因和解決方法
當(dāng)使用 IntelliJ IDEA 創(chuàng)建 Spring Framework 項(xiàng)目時(shí),springframework 出現(xiàn)紅色可能是因?yàn)橄嚓P(guān)的 Spring Framework 依賴沒有正確加載或項(xiàng)目的配置有問題,本文給大家介紹了一些常見的原因和解決方法,需要的朋友可以參考下2023-09-09