admin管理员组

文章数量:1295855

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

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

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

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

Share Improve this question asked Apr 10, 2013 at 6:32 user1734084user1734084 131 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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).

本文标签: javascriptwhy Websocket onmessage not firingStack Overflow