websocket 的初步使用与封装js

1 如何使用 websocket 



	
		
		
		
	
	
	
	

2.封装的ws.js

(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 = {});



3.如何解决websocket 断连

        方法一:

        前端处理方式

        在 this.socket.onopen 中添加定时器

this.socket.onopen = function() {
	$.onopen();
	setInterval(function(){
              $.send("success");
	},5000);
};

        方法二:

        后台处理方式 (后台在websocket这个接口中进行轮询,前端根据拿到的请求信息做判断)

        在this.socket.onmessage 中做操作

this.socket.onmessage = function(message) {
	// 服务器保持链接的心跳信息
	if("Linking..."==message.data){
	    return true;
	}
	$.onmessage(message);
};


 
 

你可能感兴趣的:(websocket 的初步使用与封装js)