var ws;//websocket实例
var lockReconnect = false;//避免重复连接
let wsUrl = 'ws://' + window.location.host + '/Socket';
let ping = 1001
let pong = 1002
var newsList = [];//存放订单
//调用websocket
//创建WebSocket连接
const createWebSocket = (wsUrl) =>{
try {
if ("WebSocket" in window) {
console.log("您的浏览器支持 WebSocket!");
ws = new WebSocket(wsUrl);
initEventHandle();
} else {
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
}catch (e){
console.log("异常信息: " + e)
reconnect(wsUrl);
}
}
//初始化
const initEventHandle = () =>{
ws.onopen = function (event){
var sendData = {
"code": ping};
ws.send(JSON.stringify(sendData));
//可以看到 "连接正在打开"并没有被打印,说明open对应的就是OPEN状态;
if (ws.readyState == WebSocket.CONNECTING) {
console.log('连接正在打开');
}
if (ws.readyState == WebSocket.OPEN) {
console.log('连接已打开');
}
// sendMsg();
console.log('已经建立连接');
auditMsgCount();
//心跳检测重置
heartCheck.reset
【websocket】
最新推荐文章于 2024-04-22 22:33:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)