HTML and CSS Reference
In-Depth Information
socket.onopen = function(event) {
console.log("Connection established.");
// Initialize any resources here and display
some user-friendly messages.
var label =
document.getElementById("status-label");
label.innerHTML = "Connection established!";
}
It's a good practice to provide your users with the appropriate feedback while they
are waiting for the connection to open. WebSockets are definitely fast, but the Inter-
net connection might be slow!
onmessage
The onmessage event is the client's ear to the server. Whenever the server sends
some data, the onmessage event is fired. Messages might contain plain text, im-
ages, or binary data. It's up to you how that data will be interpreted and visualized:
socket.onmessage = function (event) {
console.log("Data received!");
}
Checking for data types is pretty easy. Here is how we can display a string response:
socket.onmessage = function (event) {
if (typeof event.data === "string") {
// If the server has sent text data, then
display it.
var label =
document.getElementById("status-label");
label.innerHTML = event.data;
}
}
Search WWH ::




Custom Search