Working with string messages
suggest changeThe handler argument is a MessageEvent. message === value compares that event with a string, so the condition is false. The text is message.data.
const wsHost = "ws://my-sites-url.com/path/to/echo-web-socket-handler";
const ws = new WebSocket(wsHost);
const value = "an example message";
//onmessage : Event Listener - Triggered when we receive a message from the server
ws.onmessage = function(message) {
if (message === value) {
console.log("The echo host sent the correct message.");
} else {
console.log("Expected: " + value);
console.log("Received: " + message);
}
};
//onopen : Event Listener - event is triggered when the WebSocket readyState changes to open, which means we can send and receive messages
ws.onopen = function() {
//send is used to send the message to server
ws.send(value);
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents