lws-minimal-ws-server前端分析

index.html

index.html是前端入口

html 复制代码
<html>
 <head>
  <meta charset=utf-8 http-equiv="Content-Language" content="en"/>
  <!-- 引入js -->
  <script src="/example.js"></script>
 </head>
	<body>
		<img src="libwebsockets.org-logo.svg">
		<img src="strict-csp.svg"><br>
	
		LWS chat <b>minimal ws server example</b>.<br>
		Chat is sent to all browsers open on this page.
		<br>
		<br>
		<!-- 文本框 -->
		<textarea id=r readonly cols=40 rows=10></textarea><br>
		<!-- 输入框 -->
		<input type="text" id=m cols=40 rows=1>
		<!-- 发送按键 -->
		<button id=b>Send</button>
	</body>
</html>

example.js

example.js 为index.html提供了处理的逻辑

js 复制代码
function get_appropriate_ws_url(extra_url)
{
	var pcol;
	// 获得页面上的url
	var u = document.URL;

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

	// 去掉http://或者https://
	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("/");

	/* + "/xxx" bit is for IE10 workaround */

	//回来的url就城了ws://地址或者wss://地址
	return pcol + u[0] + "/" + extra_url;
}

//创建ws服务
function new_ws(urlpath, protocol)
{
	return new WebSocket(urlpath, protocol);
}

//加载监听
document.addEventListener("DOMContentLoaded", function() {
	
	//创建ws服务
	var ws = new_ws(get_appropriate_ws_url(""), "lws-minimal");
	try {
		//ws启动时
		ws.onopen = function() {
			//不禁用输入框和按键
			document.getElementById("m").disabled = 0;
			document.getElementById("b").disabled = 0;
		};
	
		//ws接收到数据包时
		ws.onmessage =function got_packet(msg) {
			//把收到的内容写到文本框加回车
			document.getElementById("r").value =
				document.getElementById("r").value + msg.data + "\n";
			//调整scrollTop
			document.getElementById("r").scrollTop =
				document.getElementById("r").scrollHeight;
		};
	
		//ws连接关闭时
		ws.onclose = function(){
			// 输入框和发送按键禁用
			document.getElementById("m").disabled = 1;
			document.getElementById("b").disabled = 1;
		};
	} catch(exception) {
		alert("<p>Error " + exception);  
	}
	
	//按键点击发送
	function sendmsg()
	{
		//发送内容
		ws.send(document.getElementById("m").value);
		//清空内容
		document.getElementById("m").value = "";
	}
	
	//为b按键增加一个click监听
	document.getElementById("b").addEventListener("click", sendmsg);
	
}, false);
相关推荐
ZC跨境爬虫6 小时前
跟着 MDN 学 HTML day_9:(信件语义标记)
前端·css·笔记·ui·html
前端老石人6 小时前
HTML 字符引用完全指南
开发语言·前端·html
幼儿园技术家7 小时前
前端如何设计权限系统(RBAC / ABAC)?
前端
前端摸鱼匠8 小时前
Vue 3 的v-bind合并行为:讲解v-bind与普通属性合并的规则
前端·javascript·vue.js·前端框架·ecmascript
REDcker9 小时前
浏览器端Web程序性能分析与优化实战 DevTools指标与工程清单
开发语言·前端·javascript·vue·ecmascript·php·js
donecoding10 小时前
一个 sudo 引发的血案:npm 全局包权限错乱彻底修复
前端·node.js·前端工程化
风骏时光牛马10 小时前
Raku正则匹配与数据批量处理实操案例
前端
nbwenren10 小时前
2026实测:Gemini 3 镜像站视觉能力实践——拍照原型图,一键生成 HTML+CSS 代码
前端·css·html
Lee川10 小时前
Prisma 实战指南:像搭积木一样设计古诗词数据库
前端·数据库·后端