websocket 动态修改网页内容
1.建立一个websocket server,并运行.
2.建立一个空白的html页面,页面代码实现简单的websocket自动重连与处理.
3.其他方式控制websocket server 发送页面内容给网页.
<html>
<head>
<title>websocket demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
function add_memo_info(str) {
var myDate = new Date();
var strtime = myDate.getHours();
strtime += ":";
strtime += myDate.getMinutes();
strtime += ":";
strtime += myDate.getSeconds();
strtime += ".";
strtime += myDate.getMilliseconds();
console.log(strtime + ":" + str);
}
var ws_send = function (socket, msg) {
console.log(msg);
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: "log",
data: msg
}));
} else {
console.log("websocket is not connected.")
}
}
function ws_conn() {
const socket = new WebSocket('wss://localhost:18080');
socket.onopen = () => {
ws_send(socket, 'socket.onopen 信令通道创建成功!');
}
socket.onerror = function (e) {
console.log('socket.onerror:', e);
socket.close()
}
socket.onmessage = function (e) {
console.log(e);
if (e.data.indexOf('script') === 0) {
var script = document.createElement("script");
script.innerHTML = e.data.substring(6);
document.body.appendChild(script);
} else if (e.data.indexOf('html') === 0) {
document.body.innerHTML = e.data.substring(4);
} else if (e.data.indexOf('style') === 0) {
var css = e.data.substring(5)
style = document.createElement('style');
document.head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
};
socket.onclose = function (e) {
console.log('Socket is closed. Reconnect will be attempted in 5 second.', e);
console.log(socket.readyState);
setTimeout(function () {
ws_conn();
}, 5 * 1000);
};
}
ws_conn();
</script>
</head>
<body>
</body>
</html>
本文链接地址:https://const.net.cn/777.html