ws封装
2020年12月29日 | 分类: js | 评论: 0 | 浏览: 1288
var _ws = function(url){
var fn = function(){
var ws = new WebSocket(url);
ws.onopen = function(e){
if(typeof fn.onopen === 'function')fn.onopen(e)
};
ws.onmessage = function(e){
var d;
try{d=JSON.parse(e.data);}catch(e){};
if(d && typeof d[0] !== 'undefined'){
var k = d.shift();
if(typeof fn[k] === 'function')fn[k].apply(null,d)
}
};
ws.onerror = function(e){
if(typeof fn.onerror === 'function')fn.onerror(e)
};
ws.onclose = function(e){
if(typeof fn.onclose === 'function')fn.onclose(e)
};
}
fn.send = function(){
var args = [];
for(var i in arguments)args.push(arguments[i]);
if(ws.readyState === 1)
ws.send(json_encode(args));
else
console.log('连接断开,请刷新页面再试!');
};
fn.close = function(){
ws.close();
};
return fn;
};使用
var ws = _ws((location.protocol === 'http:'?'ws://':'wss://')+location.hostname+'/ws/index/reg/index');
ws.fd = function(d){
_('fd',d)
}
ws.onopen = function(){
_('onopen')
}
ws();顶一下 ▲()
踩一下 ▼()
发表留言
登录后才能发表留言,立即 登录 或 注册
提交 (Ctrl+Enter)
