基于socket通信,spring
也有自己的socket通信服务:websocket
,这次就介绍如何在spring项目中使用websocket
进行通信交互。
后台:spring boot;前台:angularjs
后台建立服务
首先我们先建立起后台的服务,以实现进行socket连接。
1.引入websocket依赖
建立好一个maven项目之后,我们需要在xml
中引入websocket
的相关 依赖:
org.springframework.boot
spring-boot-starter-websocket
org.webjars
webjars-locator-core
org.webjars
sockjs-client
1.0.2
org.webjars
stomp-websocket
2.3.3
org.webjars
bootstrap
3.3.7
org.webjars
jquery
3.1.0
2.配置类
引入依赖后,就需要我们进行配置类的编写:
public class WebSocketConfig {}
这个类需要实现一个接口,来帮助我们进行socket
的连接,并接受发送过来的消息。比如下面这样:
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.控制器
这时我们要建立一个供前台访问的接口来发送消息。
@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.客户端界面
Hello WebSocket
Greetings
这部分没什么说的,主要就是其中引的连个js文件:
这两个文件帮助我们利用sockjs
和stomp
实现客户端。
创建逻辑
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("" + message + " ");
}
$(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/m...
https://docs.spring.io/spring...
https://docs.spring.io/spring...