我希望使用websocket构建一个服务器,他主要的功能是,当某个事件发生的时候例如自动保存,能够给前端发送一个字符串, 这里前端使用的是html,用浏览器打开,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>MathJax example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.9/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>
<body>
<div style="font-size:30px" id="math">
</div>
</body>
<script>
var ws = new WebSocket("ws://localhost:8080/ws");
ws.onopen = function () {
console.log("连接成功");
};
ws.onmessage = function (event) {
console.log("收到消息:" + event.data); // 接收后端发送的消息
document.getElementById("math").innerHTML = event.data
MathJax.Hub.Queue(function () {
MathJax.Hub.Typeset("div#math"); // render the latex code using mathjax
});
};
ws.onclose = function () {
console.log("连接关闭");
};
</script>
</html>
我简单的写了一下后端
(require 'websocket)
(defvar ws nil)
(defvar wss nil)
(setq wss
(websocket-server
8080 ))
(setq ws (websocket-open
"ws://localhost:8080"
:on-open (lambda (ws) (message "Connected!"))
:on-message (lambda (ws frame) (message "Received: %s" (websocket-frame-payload frame)))
:on-close (lambda (ws) (message "Closed!"))))
(defun send-string-to-frontend ()
(when ws
(message "this")
(let ((str "this"))
(websocket-send-text ws str))))
(add-hook 'after-save-hook 'send-string-to-frontend) ; 添加保存后的钩子函数
虽然在前端里f12 检查能够发现
但是并没有吧字符串上传到客户端,请问是哪里有问题