SpringBoot 集成WebSocket广播模式
1.添加maven依赖
<!--thymeleaf模板依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加websocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置WebSocket
/**
* 配置WebSocket
* @author 陈梓平
* @date 2017/10/26.
*/
@Configuration
//注解用于开启使用STOMP协议来传输基于代理(MessageBroker)的消息
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
/**
* 配置消息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic","/user");//服务器发送给客户端的前缀
//registry.setApplicationDestinationPrefixes("/app");//设置客户端发送给服务器的前缀
// registry.setUserDestinationPrefix("/user/");//用户目标的前缀
}
/**
*注册一个Stomp的节点(endpoint),并指定使用SockJS协议。
* @param stompEndpointRegistry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
//通过/app/clientLink来发送消息到服务端。
//添加访问域名限制可以防止跨域socket连接
stompEndpointRegistry.addEndpoint("/clientLink").withSockJS();
}
}
3.Controller测试
/**
* Controller测试
* @author 陈梓平
* @date 2017/10/26.
*/
@Controller
@RequestMapping
public class TestController {
@MessageMapping("/send")
@SendTo("/topic/msgInfo")
public MsgInfo msgInfo(String msg,String name){
MsgInfo msgInfo = new MsgInfo();
msgInfo.setCreator(name);
msgInfo.setMsgBody(msg);
msgInfo.setsTime(Calendar.getInstance());
return msgInfo;
}
@GetMapping(value = "ws")
public String ws(){
return "ws";
}
}
4、前端html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Boot+WebSocket+广播式</title>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script src="js/jquery-1.11.3.js"/>
</head>
<body onload="disconnect()">
<div>
<button id="connect" onclick="connect();">连接</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的名字</label><input type="text" id="name" />
<label>输入你的内容</label><input type="text" id="content" />
<button id="sendName" onclick="sendName();">发送</button>
</div>
<p id="respcontent"></p>
<script>
var stompClient = null;
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
/*$("#respcontent").html();*/
}
function connect() {
var socket = new SockJS('/clientLink'); //1
stompClient = Stomp.over(socket);//2
stompClient.connect({}, function(frame) {//3
setConnected(true);
console.log('开始进行连接Connected: ' + frame);
stompClient.subscribe('/topic/msgInfo', function(response){ //4
console.log("response:"+response);
showResponse(JSON.parse(response.body));
});
});
}
function sendName() {
var name = $('#name').val();
var content = $('#content').val();
stompClient.send("/send", {}, JSON.stringify({ 'msg': content , 'name': name }));//5
}
function showResponse(message) {
var response = $("#respcontent");
var json = JSON.stringify(message);
console.log("json:内容啊"+json);
response.append("<br></br>"+json);
}
</script>
</body>
</html>
注:需要引入stomp.js和sockjs.min.js
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
- -