基于socket通信,spring
也有自己的socket通信服務:websocket
,這次就介紹如何在spring項目中使用websocket
進行通信交互。
后臺:spring boot;前臺:angularjs
后臺建立服務
首先我們先建立起后臺的服務,以實現進行socket連接。
1.引入websocket依賴
建立好一個maven項目之后,我們需要在xml
中引入websocket
的相關 依賴:
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.配置類
引入依賴后,就需要我們進行配置類的編寫:
1
|
public class websocketconfig {} |
這個類需要實現一個接口,來幫助我們進行socket
的連接,并接受發送過來的消息。比如下面這樣:
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) { //注冊stomp協議節點,同時指定使用sockjs協議 registry .addendpoint( "/websocket-server" ) .setallowedorigins( "*" ) .withsockjs(); } } |
通常的配置我就不在這里解釋了,值得一提的是,我們使用了@enablewebsocketmessagebroker
這個注解,從字面上我們不難猜出,它表示支持websocket
提供的消息代理。
然后我們實現configuremessagebroker()
方法,來配置消息代理。在這個方法中,我們先調用enablesimplebroker()
來創建一個基于內存的消息代理,他表示以/topic
為前綴的消息將發送回客戶端。接著設置一個請求路由前綴,它綁定了@messagemapping
(這個后面會用到)注解,表示以/server
為前綴的消息,會發送到服務器端。
最后實現了registerstompendpoints()
方法,用來注冊/websocket-server
端點來建立服務器。
3.控制器
這時我們要建立一個供前臺訪問的接口來發送消息。
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
注解就是我們前面提到的,前臺會將消息發送到/server/hello
這里。
然后還有一個@sendto
注解,它表示服務器返回給前臺的消息,會發送到/topic/greeting
這里。
前臺客戶端
服務器部分建立好后,接著我們就要去建立客戶端部分
1.客戶端界面
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> |
這部分沒什么說的,主要就是其中引的連個js文件:
1
2
|
<script src= "/webjars/sockjs-client/sockjs.min.js" ></script> <script src= "/webjars/stomp-websocket/stomp.min.js" ></script> |
這兩個文件幫助我們利用sockjs
和stomp
實現客戶端。
創建邏輯
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(); }); }); |
這個文件主要注意connect()
和sendname()
這兩個方法。
最后實現的效果如下:
官方文檔:
https://spring.io/guides/gs/messaging-stomp-websocket/
https://docs.spring.io/spring/docs/4.3.20.release/spring-framework-reference/htmlsingle/#websocket
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000016976733