websocket 的初步使用与封装js

本文介绍了一种使用WebSocket进行实时双向通信的方法,包括HTML页面的搭建、JavaScript的封装及断连处理策略。通过具体示例展示了如何初始化WebSocket连接、发送消息以及接收服务器响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 如何使用 websocket 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="ws.js"></script>
	</head>
	<body>
	</body>
	<script>
		ws.init({
			url: "" 
                         // 后台接口地址
		}).connect();

		ws.onmessage = function(message) {
			console.log("receive:" + message.data);
		}
		ws.onopen = function() {
			this.send("adfa");
		};
	</script>

</html>

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);
};



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值