基于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