对websocket简单的封装,复制到项目里基本可以直接使用 websocket.js
class Webscoket {
constructor(url, fn) {
this.url = url;
this.fn = fn
this.lockReconnect
this.timerId;
this.connectTime = 2000;
this.heart = new heartCheck()
this.createConnect()
}
createConnect() {
this.ws = new WebSocket(this.url)
this.ws.onopen = () => {
this.heart.reset().start(this)
this.send("xxxx")
};
this.ws.onmessage = event => {
this.heart.reset().start(this);
this.fn(event)
}
this.ws.onclose = () => {};
this.ws.onerror = () => {
this.reconnect()
}
}
send(message) {
this.ws.send(message)
}
close() {
this.heart.reset()
this.ws.close()
}
reconnect() {
if (this.lockReconnect) {
return
}
this.lockReconnect = true
this.timerId && clearTimeout(this.timerId)
this.timerId = setTimeout(() => {
this.lockReconnect = false
this.ws.close()
this.createConnect()
}, this.connectTime)
}
}
class heartCheck {
constructor() {
this.timeout = 5000
this.timeoutObj = null
this.serverTimeoutObj = null
}
reset() {
clearTimeout(this.timeoutObj)
clearTimeout(this.serverTimeoutObj)
return this
}
start(websock) {
this.timeoutObj = setTimeout(() => {
websock.ws.send("xxxxx")
this.serverTimeoutObj = setTimeout(() => {
this.reset()
websock.reconnect()
}, this.timeout)
}, this.timeout)
}
}
使用
<script src="./websocket.js"></script>
<script type="text/javascript">
const ws = new Webscoket("你的ws服务器地址", (event) => {
console.log(event);
});
function reConnect() {
ws.reconnect()
}
function closeConnect() {
ws.close();
}
function sendEvent(data) {
ws.send(data);
}
</script>
|