这是我的代码,来自《HTML5 websocket 权威指南》一书。
....
<div id="output"></div>
<script>
function setup() {
output = document.getElementById("output");
ws = new WebSocket("ws://localhost:7777");
ws.onopen = function(e) {
log("Connected");
sendMessage("Hello Websocket!");
}
ws.onclose = function(e){
log("Disconnected: " + e.reason);
}
ws.onerror = function(e){
log("Error ");
}
ws.onmessage = function(e) {
log("Message received: " + e.data);
ws.close();
}
}
function sendMessage(msg){
ws.send(msg);
log("Message Sent");
}
function log(s){
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.textContent = s;
output.appendChild(p);
console.log(s);
}
setup();
</script>
但是,当我在本地主机中运行它时..输出就像这样
Connected
Message Sent
然后停下来。我知道 onmessage 事件没有触发,但我不知道为什么。可能是什么问题?谢谢
最佳答案
onmessage
仅在服务器向客户端发送消息时触发,而不是在客户端向服务器发送消息时触发(这就是您正在做的事情)。
如果您的服务器正在发回一条消息,而您的客户端没有接收到该消息,则您将需要提供更多上下文(服务器实现等)。
关于javascript - 为什么 Websocket onmessage 没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15918599/