源码如下
/**
* Module dependencies.
*/
import Emitter from "component-emitter";
/**
* Socket constructor.
*/
class Socket {
constructor(uri, opts) {
opts = opts || {};
this.uri = uri;
this.readyState = "";
this.ws = null;
this.WebSocketImpl = null;
this.reconnecting = false;
this.reconnectCounter = 0;
this.timer = null;
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.check();
}
check() {
if ("undefined" !== typeof WebSocket) {
this.WebSocketImpl = WebSocket;
} else if (typeof self !== "undefined") {
this.WebSocketImpl = self.WebSocket || self.MozWebSocket;
} else {
throw new Error("Your environment not support WebSocket.");
}
this.open();
}
open() {
this.cleanUp();
if ("closed" === this.readyState || "" === this.readyState) {
this.doOpen();
}
}
send(packets) {
if ("open" === this.readyState) {
this.write(packets);
} else {
throw new Error("Transport not open");
}
}
close() {
if ("opening" === this.readyState || "open" === this.readyState) {
this.readyState = "closed";
this.resetReconnectCounter();
this.doClose();
}
}
write(packets) {
this.ws.send(packets);
}
reconnect() {
if (this.reconnecting) {
return;
}
const self = this;
if (this.reconnectCounter >= this._reconnectionAttempts) {
this.reconnecting = false;
} else {
this.reconnectCounter++;
this.reconnecting = true;
const delay = 2000;
this.timer = setTimeout(() => {
this.reconnecting = false;
this.open();
}, delay);
}
}
doOpen() {
const uri = this.uri;
this.ws = new this.WebSocketImpl(uri);
this.addEventListeners();
}
doClose() {
if (typeof this.ws !== "undefined") {
this.ws.close();
}
}
addEventListeners() {
const self = this;
this.ws.onopen = function() {
self.onOpen();
};
this.ws.onclose = function() {
self.onClose();
};
this.ws.onmessage = function(ev) {
console.log(ev)
self.onData(ev.data);
};
this.ws.onerror = function(e) {
self.onError("websocket error", e);
};
}
onOpen() {
this.readyState = "open";
this.writable = true;
this.emit("open");
}
onClose() {
this.readyState = "closed";
this.emit("close");
if (this._reconnection) {
this.reconnect();
}
}
onData(packet) {
const data = this.decodePacket(packet);
this.onPacket(data);
}
onPacket(packet) {
console.log(packet)
this.emit("packet", packet);
}
onError(msg, desc) {
let err = new Error(msg);
err.type = "TransportError";
err.description = desc;
this.emit("error", err);
}
decodePacket(packet) {
return packet;
}
reconnection(v) {
this._reconnection = v;
}
reconnectionAttempts(v) {
this._reconnectionAttempts = v;
}
resetReconnectCounter() {
this.reconnectCounter = 0;
}
cleanUp() {
clearTimeout(this.timer);
}
}
Emitter(Socket.prototype);
export default Socket;
原文:https://www.cnblogs.com/sturrbon/p/11762746.html