<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Spring Boot WebSocket+广播式</title>
</head>
<body>
<noscript>
<h2 style="color:#ff0000">貌似你的浏览器不支持websocket</h2>
</noscript>
<div>
<div>
<button id="connect" onclick="connect()">连接</button>
<button id="disconnect" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的名字</label> <input type="text" id="name"/>
<br>
<label>输入消息</label> <input type="text" id="messgae"/>
<button id="send" onclick="send();">发送</button>
<p id="response"></p>
</div>
</div>
<script src="https://cdn.bootcss.com/sockjs-client/1.0.0/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
let stompClient = null
//gateway网关的地址
let host = "http://localhost:29101/monitor";
let headers = {
'authorization':'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzOjQ6MWQ4MTA4YjMyM2VhNzU0NzoxNDE4MTI3MDA5NDY4NTE4NDAwIiwiZXhwIjoxNjI2OTUwMDAxfQ.h_5Ug7fZQ5QiGSSakkG4hdcvpmTKMIQq_LQloIAUPEg'
};
var tryTimes=0;//重连次数
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
}
// SendUser ***********************************************
/*function connect() {
//地址+端点路径,构建websocket链接地址,注意,对应config配置里的addEndpoint
var socket = new SockJS(host+'/ws' + '?token=4567');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected:' + frame);
//监听的路径以及回调
stompClient.subscribe('/user/queue/sendUser', function(response) {
showResponse(response.body);
});
});
}*/
function connect() {
//地址+端点路径,构建websocket链接地址,注意,对应config配置里的addEndpoint
var socket = new SockJS(host + '/ws' + '?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzOjQ6MWQ4MTA4YjMyM2VhNzU0NzoxNDE4MTI3MDA5NDY4NTE4NDAwIiwiZXhwIjoxNjI2OTUwMDAxfQ.h_5Ug7fZQ5QiGSSakkG4hdcvpmTKMIQq_LQloIAUPEg');
stompClient = Stomp.over(socket);
console.log(stompClient)
stompClient.connect(headers, function (frame) {
setConnected(true);
heartCheck.reset().start(); //心跳检测重置
tryTimes= 0;//重置重连次数
console.log('Connected:' + frame);
//监听的路径以及回调
/*stompClient.subscribe('/topic/box-package/SZBATT202103221723290344', function (response) {
showResponse(response.body);
});*/
});
}
function reconnect() {
if(tryTimes>10){
alert("重连次数以达上限 连接失败")
return;
}
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
connect();
}, 3000);
}
function disConnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function send() {
var name = $('#name').val();
var message = $('#messgae').val();
/*//发送消息的路径,由客户端发送消息到服务端
stompClient.send("/sendServer", {}, message);
*/
/*// 发送给所有广播sendTopic的人,客户端发消息,大家都接收,相当于直播说话 注:连接需开启 /topic/sendTopic
stompClient.send("/sendAllUser", {}, message);
*/
/* 这边需要注意,需要启动不同的前端html进行测试,需要改不同token ,例如 token=1234,token=4567
* 然后可以通过写入name 为token 进行指定用户发送
*/
let cmd = "box-realtime";
/*stompClient.send("/cmd", headers, JSON.stringify({CMD: "box-package", data: { deviceCode: "1194533058445", subCode: "1" }}));
stompClient.subscribe('/topic/box-package/1194533058445/1', function (response) {
showResponse(response.body);
});*/
stompClient.send("", headers, JSON.stringify({CMD: cmd, data: {deviceCode: "2021855394218903"}}));
stompClient.subscribe('/topic/box-realtime/2021855394218903', function (response) {
showResponse(response.body);
});
}
function showResponse(message) {
var response = $('#response');
response.html(message);
//heartCheck.reset().start();
}
//心跳检测与重连
var heartCheck = {
timeout: 3000, //5s发一次心跳
timeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);//清除定时任务
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setInterval(function(){
let cmd = "box-heartbeat";
//这里发送一个心跳到后端指定路由,后端该路径收到将再发一条消息到前端指定路由,从而完成一次交互(消息content可以为空 只要能到达路由就可以)
stompClient.send("/cmd", headers, JSON.stringify({CMD: cmd, data: {deviceCode: "2021855394218903"}}));
console.log("ping!");
//如果超过一定时间还没重置才会执行到这,说明后端主动断开了
/*
self.serverTimeoutObj = setTimeout(function(){
disConnect();
connect();
}, self.timeout); */
}, this.timeout);
}
}
</script>
</body>
</html>