HTML and CSS Reference
In-Depth Information
The first step on the client side is to create a new
WebSocket
instance:
var socket =
new WebSocket(
"ws://localhost:8080/"
);
Then, assign event handlers to the
socket
object. In this first example,
the server will wait 10 seconds and
then close the connection, so you
just need to watch the
onopen
and
onclose
events:
socket.onopen = function () {
log("Socket has been opened!");
}
socket.onclose = function () {
log("Socket has been closed");
}
Now let's look at what happens when the server sends a message. In
the browser, you have to handle the
onmessage
event:
socket.onmessage = function(msg) {
log(msg.data);
}
The
data
attribute of the event
handler argument contains the
message from the server; in this
case, the current data and time
every 10 seconds.
You can also control the connection
from the browser with the
close
method on the
socket
object:
socket.close();