我有一個運行在 ESP32 上的 websocketserver,它運行良好。
我的問題是,如果我通過網站向服務器發送訊息,ESP32 上的套接字服務器僅第一次執行 .send(message) 并且不再發送任何訊息。
如果我從 chrome 中的 developertools/console 發送訊息,它每次都有效。
在這一點上,我想我的問題似乎不在服務器端,而是在客戶端。
這是我在 chrome 中運行的 html/javascript 代碼:
<!DOCTYPE html>
<head>
<title>WH_Quiz</title>
<style>
body {
background: url(Images/SET_1/A1_INTRO.png) no-repeat center center fixed;
-webkit-background-size: cover;
background-size: cover;
}
</style>
</head>
<body>
<script>
// clear localStorage
window.localStorage.clear();
// open websocket
var url = "ws://192.168.4.1:1337";
websocket = new WebSocket(url);
websocket.onopen = function (event) {
console.log('websocket is open');
websocket.send("L");
};
// Keep track of clicked keys
var isKeyPressed = {
'a': false, // ASCII code for 'a'
'b': false, // ASCII code for 'b'
// ... Other keys to check for custom key combinations
};
document.onkeydown = (keyDownEvent) => {
// Prevent default key actions, if desired
keyDownEvent.preventDefault();
// Track down key click
isKeyPressed[keyDownEvent.key] = true;
// Check described custom shortcut
if (isKeyPressed['a']) { //for example we want to check if a is clicked
//do something
console.log('a has been pressed');
websocket.onopen = function (event) {
console.log('a has been pressed and wesocket is open');
window.location.href = '1_1.html'; // ?ffne Fragenkatalog 1
websocket.send("4G");
};
};
// Check described custom shortcut
if (isKeyPressed['b']) { //for example we want to check if b is clicked
//do something
console.log('b has been pressed');
websocket.onopen = function (event) {
window.location.href = '2_1.html'; // ?ffne Fragenkatalog 2
websocket.send("4R");
};
};
};
</script>
</body>
</html>
在我的控制臺日志中,我可以看到它進入了“isKeyPressed”if 陳述句,但沒有執行“websocket.onopen = function (event)”。
我究竟做錯了什么?
uj5u.com熱心網友回復:
websocket.onopen僅在套接字第一次打開時觸發。由于此時它已經打開,您應該可以直接呼叫 send 函式。
換句話說:
if (isKeyPressed['b']) { //for example we want to check if b is clicked
//do something
console.log('b has been pressed');
websocket.onopen = function (event) {
window.location.href = '2_1.html'; // ?ffne Fragenkatalog 2
websocket.send("4R");
};
};
變成:
if (isKeyPressed['b']) { //for example we want to check if b is clicked
//do something
console.log('b has been pressed');
window.location.href = '2_1.html'; // ?ffne Fragenkatalog 2
websocket.send("4R");
};
uj5u.com熱心網友回復:
我對 websockets 不太了解,但看起來 onopen() 函式就像 discord.js 中的 onready() 函式。它僅在腳本啟動/打開 websocket 時運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491980.html
標籤:javascript html 网络套接字 esp32 arduino-esp32
上一篇:當相鄰單元格在谷歌表格中為空時,如何列出非空單元格?
下一篇:從表中洗掉行的功能不起作用
