index.html
index.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提供了處理的邏輯
function get_appropriate_ws_url(extra_url)
{var pcol;// 獲得頁面上的urlvar 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";//調整scrollTopdocument.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);