1

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.