WebSocket简单封装

WebSocket简单封装:
(function($) {
$.config = {
url: ‘’, //链接地址
};

$.init=function(config) {
	this.config = config;
	return this;
};


/**
 * 连接webcocket
 */
$.connect = function() {
	var protocol = (window.location.protocol == 'http:') ? 'ws:' : 'wss:';
	this.host = protocol + this.config.url;


	window.WebSocket = window.WebSocket || window.MozWebSocket;
	if(!window.WebSocket) { // 检测浏览器支持  
		this.error('Error: WebSocket is not supported .');
		return;
	}
	this.socket = new WebSocket(this.host); // 创建连接并注册响应函数  
	this.socket.onopen = function() {
		$.onopen();
	};
	this.socket.onmessage = function(message) {
		$.onmessage(message);
	};
	this.socket.onclose = function() {
		$.onclose();
		$.socket = null; // 清理  
	};
	this.socket.onerror = function(errorMsg) {
		$.onerror(errorMsg);
	}
	return this;
}


/**
 * 自定义异常函数
 * @param {Object} errorMsg
 */
$.error = function(errorMsg) {
	this.onerror(errorMsg);
}


/**
 * 消息发送
 */
$.send = function(message) {
	if(this.socket) {
		this.socket.send(message);
		return true;
	}
	this.error('please connect to the server first !!!');
	return false;
}


$.close = function() {
	if(this.socket != undefined && this.socket != null) {
		this.socket.close();
	} else {
		this.error("this socket is not available");
	}
}


/**
 * 消息回調
 * @param {Object} message
 */
$.onmessage = function(message) {


}


/**
 * 链接回调函数
 */
$.onopen = function() {


}


/**
 * 关闭回调
 */
$.onclose = function() {


}


/**
 * 异常回调
 */
$.onerror = function() {

}

})(ws = {});

使用方法:
ws.init({
url: “//xxx”
}).connect();

	ws.onmessage = function(message) {
		console.log("receive:" + message.data);
	}

	ws.onopen = function() {
		this.send("adfa");
	};

转载链接地址 https://blog.csdn.net/u014692324/article/details/80279160

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值