使用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)行配置類的編寫(xiě):
public class WebSocketConfig {}
這個(gè)類需要實(shí)現(xiàn)一個(gè)接口,來(lái)幫助我們進(jìn)行socket的連接,并接受發(fā)送過(guò)來(lái)的消息。比如下面這樣:
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()方法,來(lái)配置消息代理。在這個(gè)方法中,我們先調(diào)用enableSimpleBroker()來(lái)創(chuàng)建一個(gè)基于內(nèi)存的消息代理,他表示以/topic為前綴的消息將發(fā)送回客戶端。接著設(shè)置一個(gè)請(qǐng)求路由前綴,它綁定了@MessageMapping(這個(gè)后面會(huì)用到)注解,表示以/server為前綴的消息,會(huì)發(fā)送到服務(wù)器端。
最后實(shí)現(xiàn)了registerStompEndpoints()方法,用來(lái)注冊(cè)/websocket-server端點(diǎn)來(lái)建立服務(wù)器。
3.控制器
這時(shí)我們要建立一個(gè)供前臺(tái)訪問(wèn)的接口來(lá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>
這部分沒(méi)什么說(shuō)的,主要就是其中引的連個(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的通信過(guò)程與實(shí)現(xiàn)方法詳解
- android利用websocket協(xié)議與服務(wù)器通信
- C# websocket及時(shí)通信協(xié)議的實(shí)現(xiàn)方法示例
- 使用 Spring Boot 實(shí)現(xiàn) WebSocket實(shí)時(shí)通信
- Spring Boot 開(kāi)發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)
- .NET實(shí)現(xiàn)WebSocket服務(wù)端即時(shí)通信實(shí)例
- WebSocket+node.js創(chuàng)建即時(shí)通信的Web聊天服務(wù)器
- Python通過(guò)websocket與js客戶端通信示例分析
- 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解
相關(guān)文章
springboot使用Mybatis-plus分頁(yè)插件的案例詳解
這篇文章主要介紹了springboot使用Mybatis-plus分頁(yè)插件的相關(guān)知識(shí),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05
Jmeter訪問(wèn)需要登錄的接口如何處理問(wèn)題
這篇文章主要介紹了Jmeter訪問(wèn)需要登錄的接口如何處理問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
springMVC配置環(huán)境實(shí)現(xiàn)文件上傳和下載
這篇文章主要為大家詳細(xì)介紹了springMVC配置環(huán)境實(shí)現(xiàn)文件上傳和下載的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
JMS簡(jiǎn)介與ActiveMQ實(shí)戰(zhàn)代碼分享
這篇文章主要介紹了JMS簡(jiǎn)介與ActiveMQ實(shí)戰(zhàn)代碼分享,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12
Java?中?hashCode()?與?equals()?的關(guān)系(面試)
這篇文章主要介紹了Java中hashCode()與equals()的關(guān)系,ava中hashCode()和equals()的關(guān)系是面試中的??键c(diǎn),文章對(duì)hashCode與equals的關(guān)系做出詳解,需要的小伙伴可以參考一下2022-09-09
SpringBoot實(shí)現(xiàn)PDF添加水印的示例
本文主要介紹了SpringBoot實(shí)現(xiàn)PDF添加水印的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
IDEA使用MyBatisCodeHelperPro來(lái)generator代碼的詳細(xì)教程
這篇文章主要介紹了IDEA使用MyBatisCodeHelperPro來(lái)generator代碼的詳細(xì)教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
數(shù)據(jù)庫(kù)CURD必備搭檔mybatis?plus詳解
這篇文章主要為大家介紹了數(shù)據(jù)庫(kù)CURD必備搭檔mybatis?plus詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

