简单介绍
常规的websocket连接和普通的TCP基本上没有什么差别的,全双工的通信方式,点对点通信方式。
stomp在websocket上提供了一中基于帧线路格式(frame-based wire format),就是在我们的websocket(TCP)上面加了一层协议,使双方遵循这种协议来发送消息。
基于stomp的websocket和springboot的整合
相关配置类
package com.zhao.sian.config;
import org.springframework.beans.factory.annotation.Autowired;
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;
import com.deltaww.dkam.learning.config.interceptor.HeaderInterceptor;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Autowired
private H5HeaderInterceptor h5HeaderInterceptor;
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry
// websocket的连接路径
.addEndpoint("/api/v1/../ws")
// 设置跨域
.setAllowedOrigins("*")
// 设置拦截器
.addInterceptors(HeaderInterceptor)
// 支持 SockJS
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
设置topic通信
registry.enableSimpleBroker("/topic", "/queue");
}
}
事件处理监听器
package com.zhao.sian.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class WebsocketEventListener {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Async
@EventListener
public void handleSessionDisconnect(SessionDisconnectEvent event) {
}
@Async
@EventListener
public void handleSessionConnected(SessionConnectedEvent event) {
String sessionId = (String) event.getMessage().getHeaders().get("simpSessionId");
log.info("Connection established {}", sessionId);
}
@Async
@EventListener
public void handleSessionConnect(SessionConnectEvent event) throws Exception {
}
}
消息订阅controller
package com.zhao.sian.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
@Api(tags = "WSEventController")
@RestController
@RequestMapping("/api/v1/.../ws")
public class WSEventController {
@MessageMapping("/topic/h5")
public void recodeH5Time(String message) {
}
@MessageMapping("/topic/doc")
public void recodeDocTime(String message) {
}
}
前端测试程序
<html>
<head>
<title>ReadTime WebSocket</title>
<script src="./js/sockjs-1.4.0.js"></script>
<script src="./js/stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
var sessionId;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS('http://localhost:3030/ws');
stompClient = Stomp.over(socket);
stompClient.connect(headers, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
sessionId = stompClient.ws._transport.url.split("/")[8];
stompClient.subscribe('/topic/watch', function(messageOutput) {
}, headers);
});
}
function disconnect() {
if(stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendMessage() {
stompClient.send("/topic/h5", {}, sessionId);
}
</script>
</head>
<body onl oad="disconnect()">
<div>
<div>
<p>Course Id :</p><input type="text" id="courseId" placeholder="Course Id" value="5e4520bc02743900018e863b"/>
</div>
<br />
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<br />
<div id="conversationDiv">
<!--
<p>Read Time :</p><input type="text" id="readTime" placeholder="Read Time..."/>
-->
<button id="sendMessage" onclick="sendMessage();">Send</button>
<p>Response :</p><p id="response"></p>
</div>
</div>
</body>
</html>