为什么 Websocket onmessage 没有触发 [英] why Websocket onmessage not firing

查看:267
本文介绍了为什么 Websocket onmessage 没有触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在《HTML5 websocket 权威指南》一书中的代码.

this my code from books "The Definitive Guide to 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>

但是,当我在本地主机中运行它时......输出就像这样

but, when i'm running it in localhost.. the output just like this

Connected
Message Sent

然后停下来.我知道 onmessage 事件没有触发,但我不知道为什么.可能是什么问题?谢谢

and stop until that. i knew event onmessage is not firing, but i dont know why. what could possibly be the problem? thanks

推荐答案

onmessage 只会在服务器向客户端发送消息时触发,而不会在客户端向服务器发送消息时触发 (这就是你在做什么).

onmessage will only fire when the server sends a message to the client, not when the client is sending a message to the server (which is what you're doing).

如果您的服务器正在发回一条消息并且您的客户端没有接收到该消息,您将需要提供更多上下文(服务器实现等).

If your server is sending back a message and that isn't being picked up by your client, you're going to need to provide a bit more context (server implementation, etc).

这篇关于为什么 Websocket onmessage 没有触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆