javascript实现websocket的连接写法 #2

//自动获取当前ip和端口,如果您的网站和websocket连接地址一样
function get_appropriate_ws_url(extra_url) {
	var pcol;
	var u = document.URL;

	/*
	 * We open the websocket encrypted if this page came on an
	 * https:// url itself, otherwise unencrypted
	 */

	if(u.substring(0, 5) == "https") {
		pcol = "wss://";
		u = u.substr(8);
	} else {
		pcol = "ws://";
		if(u.substring(0, 4) == "http")
			u = u.substr(7);
	}
	u = u.split('/');

	return pcol + u[0] + "/" + extra_url;
}

function new_ws(urlpath, protocol) {

	if(typeof MozWebSocket != "undefined")
		return new MozWebSocket(urlpath, protocol);

	return new WebSocket(urlpath, protocol);
}
//连接错误的常识次数  当连接5次时不在常识连接
var connectCount = 0;
function socketConnect() {
	window.ws = new_ws("ws://192.168.3.247:7681/ws", "devices-protocol");
	//window.ws = new_ws(get_appropriate_ws_url("/ws"), "devices-protocol");
	try {
		ws.onopen = function() {
			console.log('open socket');
		}

		ws.onmessage = function got_packet(msg) {
			connectCount = 0;
			if(typeof msg.data == "string") { //如果是字符串
				try {
					console.log(msg.data);
				} catch(e) {
					
				}
			} else { 
                                 //如果是json等数据,如果有高并发数据,建议推荐使用FileReader 把字符串读成二进制
				var reader = new FileReader();
				reader.readAsBinaryString(msg.data, 'utf-8');
				reader.onload = function(e) {
					try {
						console.info(reader.result + "====");
						//处理逻辑数据
					} catch(e) {
						//TODO handle the exception
						console.log("数据转换异常");
					}

				}

			}
		}
		ws.onclose = function() {
			console.log('close socket');
			if(connectCount <= 5) { //如果连接失败常识重新连接
				connectCount++;
				socketConnect();
			}
		}
		ws.onerror = function() {
			console.log("websocket error");
		};
	} catch(exception) {
		alert('Error' + exception);
	}
}
//初始化连接
socketConnect();