龙空技术网

随意开发一个websocket通信DEMO

前端大伟 1136

前言:

今天同学们对“ajax数组push”大约比较看重,小伙伴们都需要分析一些“ajax数组push”的相关知识。那么小编在网络上汇集了一些关于“ajax数组push””的相关知识,希望朋友们能喜欢,咱们快快来了解一下吧!

随意开发一个websocket通信DEMO

示例:

连接一个免费的ws测试服务来演示此项功能,HeartBeat为心跳连接

ws://123.207.136.134:9010/ajaxchattest

希望各位小伙伴多多点赞收藏转发

源码给上:

HTML

<div>			<h1>WebSocket 通信</h1>			<div>				<div>					<textarea rows="6" id="sendMsg" style="width: 100%;"></textarea>				</div>				<div>					<div>						<button type="button" onkeydown="sendMsg()" onclick="sendMsg()">发送</button>					</div>				</div>			</div>			<div class="row">				<div class="col">					<div></div>					<div>						<div id="chartRoom">							<p>本机发送消息:<span id="receivedMsg"></span></p>							<p>服务器返回消息:<span id="getMsg"></span></p>							<a href="javascript:;" onclick="refreshConnect()" role="button">刷新连接</a>							<hr>						</div>					</div>				</div>			</div>		</div>		<script src="; integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>		<script src="./static/js/websocket.js"></script>

JS

var os = require("os");var websoketArray = [];if (typeof module === 'object') {	window.jQuery = window.$ = module.exports;};$(function() {	startConnect();});function startConnect() {	websoketArray.push(new createWebsocket("ws://123.207.136.134:9010/ajaxchattest"));}function createWebsocket(url) {	var heartCheck = {		timeout: 3000,		timeoutObj: null,		reset: function() {			clearTimeout(this.timeoutObj);			this.start();		},		start: function() {			this.timeoutObj = setTimeout(function() {				ws.send("HeartBeat");			}, this.timeout)		}	}	var ws = new WebSocket(url);	ws.onopen = (event) => {		console.log("已成功连接ws服务");		$("#chartRoom").append("<p>与 " + url + " 建立连接--成功</p>");		heartCheck.start();	}	ws.onmessage = (event) => {		console.log(event);		console.log(event.data);		if (!event.data.includes("HeartBeat")) {			$("#getMsg").html(event.data);		} else {			heartCheck.reset();		}	}	ws.onclose = function(event) {		console.log(url + "连接已关闭...");		clearTimeout(heartCheck.timeoutObj);	}	ws.onerror = function(event) {		$("#chartRoom").append("<p>与 " + url + " 建立连接--失败</p>");		ws.close();		websoketArray.splice(websoketArray.indexOf(ws), 1);		console.log(url + "连接已关闭");		setTimeout(function() {			startConnect();		}, 3000);	}	return ws;}function sendMsg() {	var msg = $("#sendMsg").val();	if (!msg) {		return;	}	$("#receivedMsg").html(msg);	if (msg !== "" && msg !== undefined) {		for (var i = 0; i < websoketArray.length; i++) {			websoketArray[i].send(msg);			$("#sendMsg").val(null);		}	}}function refreshConnect() {	for (var i = 0; i < websoketArray.length; i++) {		websoketArray[i].close();	}	setTimeout(function() {		startConnect();	}, 3000);}

标签: #ajax数组push