<html>
<head>
<meta charset=UTF-8">
<title>WebSocket</title>
</head>
<body>
<input id="token" type="text" value="e8yfgb605uswt7zthq3flh6lf0eja6owc5klf2hrcf6ne82o8p00l1w9mfmt" style="width:500px"/> token
<br/>
<input id="url" type="text" value="ws://localhost:8861/webSocketBySpring/webSocketHandler/0kzs3eyujcwk0qn0uw" style="width:500px"/>
<button onclick="connectMethod()">WebSocket链接</button>
<br/>
<input id="text" type="text" style="width:500px"/>
<button onclick="send()">发送消息</button>
<hr />
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr />
<h3>消息打印</h3> <button onclick="clearMsg()">清除</button>
<div id="message"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script type="text/javascript">
// 清除窗口消息
function clearMsg(){
document.getElementById('message').innerHTML = "";
}
var websocket = null;
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
};
// 连接服务端
function connectMethod(){
var url = document.getElementById('url').value;
var token = document.getElementById('token').value;
if('WebSocket' in window) {
console.log("WebSocket");
websocket = new WebSocket(url,[token]);
} else if('MozWebSocket' in window) {
console.log("MozWebSocket");
websocket = new MozWebSocket(url);
} else {
console.log("SockJS");
//websocket = new SockJS("localhost:8088/websocket/webSocketByTomcat/"+document.getElementById('sessionId').value);
}
//连接发生错误的回调方法
websocket.error = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
};
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
};
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
};
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
只用到了websocket = new WebSocket(url,["10869fde-f52a-43d1-893a-1cc6da9421d9"])这个创建方式,其他方式未测试,中括号的值为token。
如图:
另外后端获取请求头中的token之后,代码响应头也要加上该参数并设值,不然会报错。