websocket:⽀持前端连接+订阅要实现的功能:后端提供 可订阅的数据,前端连接成功后 订阅后 定时被推送数据。
---直接上代码---
websocket配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//添加⼀个/websocket端点,客户端就可以通过这个端点来进⾏连接;withSockJS作⽤是添加SockJS⽀持
registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//定义了两个客户端订阅地址的前缀信息,也就是客户端接收服务端发送消息的前缀信息
//定义了服务端接收地址的前缀,也即客户端给服务端发消息的地址前缀
registry.setApplicationDestinationPrefixes("/app");
}
}
定时任务 提供订阅数据
//定时任务发布消息(每⼗秒执⾏⼀次)
@Scheduled(cron = "*/10 * * * * ?")//运⾏周期时间可配
public void publicMarketValueMessage() {
//这⾥的nowDate 暂且作为订阅的内容--可更换为具体的业务数据
String nowDate = dateFormat.format(new Date());
//这⾥的destination 是订阅的地址
String destination = "/topic/echoTest/price";
log.info("websocket 【{}】定时任务发布消息==>【开始】", destination);
try {
}catch (Exception e){
<("websocket ={} 定时任务发布消息==>【异常】", destination, e);
}
}
前端测试代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="cdn.bootcss/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="cdn.bootcss/sockjs-client/1.1.4/sockjs.min.js"></script>
<script type="text/javascript" src="cdn.bootcss/stomp.js/2.3.3/stomp.min.js"></script>
<script type="text/javascript">
var stompClient = null;
websocket和socketfunction setConnected(connected) {
}
function connect() {
var socket = new SockJS('localhost:8080/websocket');//连接服务端的端点,连接以后才可以订阅⼴播消息和个⼈消息 stompClient = Stomp.over(socket);
setConnected(true);
console.log('Connected: ' + frame);
//订阅⼴播消息
stompClient.subscribe('/topic/echoTest/price', function(greeting){
showGreeting(greeting.body);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
setConnected(false);
console.log("Disconnected");
}
}
function showGreeting(message) {
var response = ElementById('response');
var p = ateElement('p');
p.style.wordWrap = 'break-word';
p.ateTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body class="easyui-layout">
<div>
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
<p id="response" ></p>
</div>
</div>
</body>
</html>
--如有问题欢迎沟通 交流--
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论