<!--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>複製代碼
/**
* 配置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();
}
}複製代碼
/**
* 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";
}
}複製代碼
<!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.jscss
<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>複製代碼
- html