add websocket example

This commit is contained in:
zedhugh committed 2023-11-22 01:30:51 +08:00
1 parent bb37fefaa2
commit 75a6ab7ffa
3 files changed
+85

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
let ws = new WebSocket("ws://127.0.0.1:4000");
ws.onopen = () => {
console.log('websocket opened');
}
ws.onclose = () => {
console.log('websocket closed');
}
ws.onmessage = (e) => {
console.log('recv:', e.data)
}
let timeout = 0;
let timer = null;
/**
* 发送消息到 Emacs
* @param {string} msg 消息内容
*/
function sendMsgToEmacs(msg) {
if (!(ws instanceof WebSocket) || ws.readyState !== WebSocket.OPEN) return;
ws.send(msg);
}
const range = 10;
function calcNextTimeout() {
return (Math.round(Math.random() * range) + 2) * 1000;
}
function schedule() {
sendMsgToEmacs(window.crypto.randomUUID());
window.clearTimeout(timer);
timeout = calcNextTimeout();
timer = window.setTimeout(schedule, timeout);
}
schedule();