基于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依賴(lài)
建立好一個(gè)maven項(xiàng)目之后,我們需要在xml
中引入websocket
的相關(guān) 依賴(lài):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<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.配置類(lèi)
引入依賴(lài)后,就需要我們進(jìn)行配置類(lèi)的編寫(xiě):
1
|
public class websocketconfig {} |
這個(gè)類(lèi)需要實(shí)現(xiàn)一個(gè)接口,來(lái)幫助我們進(jìn)行socket
的連接,并接受發(fā)送過(guò)來(lái)的消息。比如下面這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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ā)送回客戶(hù)端。接著設(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)訪(fǎng)問(wèn)的接口來(lái)發(fā)送消息。
1
2
3
4
5
6
|
@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)客戶(hù)端
服務(wù)器部分建立好后,接著我們就要去建立客戶(hù)端部分
1.客戶(hù)端界面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<!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文件:
1
2
|
<script src= "/webjars/sockjs-client/sockjs.min.js" ></script> <script src= "/webjars/stomp-websocket/stomp.min.js" ></script> |
這兩個(gè)文件幫助我們利用sockjs
和stomp
實(shí)現(xiàn)客戶(hù)端。
創(chuàng)建邏輯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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í)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000016976733