2 Star 5 Fork 4

姿势喵/nodejs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
wsclient.js 1.31 KB
一键复制 编辑 原始数据 按行查看 历史
姿势喵 提交于 2019-05-10 17:40 . 浏览器端的websocket
//浏览器的WebSocket客户端
function WSClient(uri, short) {
this.uri = uri;
this.state = 0;
this.short = short;
this.connect = function(connectCallback, errorCallback, recvCallback, closeCallback) {
if ("WebSocket" in window) {
this.ws = new WebSocket(this.uri);
// this.ws.binaryType = "arraybuffer";
this.state = 1;
let self = this;
this.ws.onopen = function() {
self.state = 2;
if(connectCallback) {
connectCallback();
}
};
this.ws.onmessage = function (evt) {
if(recvCallback) {
recvCallback(evt.data);
}
if (self.short) {
setTimeout(() => {
self.close();
}, 300);
}
};
this.ws.onclose = function() {
self.state = 0;
if(closeCallback) {
closeCallback();
}
};
this.ws.onerror = function(err) {
if(errorCallback) {
errorCallback(err);
}
};
} else {
alert("您的浏览器不支持 WebSocket!");
}
};
this.send = function(data) {
if(this.state==2) {
this.ws.send(data);
}
};
this.close = function() {
if (this.state>0) {
this.ws.close();
this.ws = null;
this.state = 0;
}
};
}
function makeWebSocket(uri, data, recv) {
let ws = new WSClient(uri, true);
ws.connect(function() {
ws.send(data);
}, function(err) {
console.error("websocket error!");
}, recv, null);
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/jinghuashuiyue2017/nodejs.git
git@gitee.com:jinghuashuiyue2017/nodejs.git
jinghuashuiyue2017
nodejs
nodejs
master

搜索帮助