after WebSocket was disconnected, I re-new a link. In the new connection, I can continue to receive and send data, but I found that ws.onmessage did not return the data after reconnection.
I think he is still waiting for the data of the address before the disconnection. What should I do?
// websocket.js
export function initWebsocket(user = {}, userType) {
socketurl = "ws://" + WEBSOKET_URL + "//////"
ws = new WebSocket(socketurl);
ws.onopen = function (evt) {
wsReadyState = evt.currentTarget.readyState;
if (wsReadyState == 1) {
//
wsPromise = new Promise((resolve, reject) => {
resolve();
})
wsPromise.then((data) => {
let wsMsgListCopy = [
...wsMsgList
];
wsMsgListCopy.forEach((msg) => {
ws.send(JSON.stringify(msg));
wsMsgList.shift();
})
})
initEventHandle();
}
};
return ws;
}
export function sendMsgByWebsccket(msg, toast, ) {
//
ws.send(JSON.stringify(msg));
}
function createWebSocket(url) {
try {
ws = new WebSocket(url);
initEventHandle();
} catch (e) {
reconnect(url);
}
}
function initEventHandle() {
ws.onclose = function () {
reconnect(socketurl);
};
ws.onerror = function () {
reconnect(socketurl);
};
}
function reconnect(url) {
if (lockReconnect) return;
lockReconnect = true;
setTimeout(function () {
createWebSocket(url);
lockReconnect = false;
}, 2000);
}
const heartCheck = {
timeout: 10000,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
const self = this;
self.serverTimeoutObj = setTimeout(function () {
ws.close();
createWebSocket(socketurl);
}, self.timeout)
}
}
// index.js
import { initWebsocket } from "../websocket"
componentDidMount() {
console.log("");
const self = this;
self.ws = initWebsocket(curUser, USER_TYPE);
self.ws.onmessage = (event) => {
const arg = JSON.parse(event.data);
//
}
}