236 Chapter 9—WebSockets
function $(a) { return document.getElementById(a); }
var ws, currentUser, ele;
window.onload = function() {
ws = new WebSocket("ws://html5.komplett.cc:8887/bc");
ws.onopen = function() {
$("status").innerHTML = 'online';
$("status").style.color = 'green';
ws.onmessage = function(e) {
var msg;
try {
msg = JSON.parse(e.data);
} catch (SyntaxError) {
$("debug").innerHTML = "invalid message";
return false;
}
If the connection is successfully established, the WebSocket’s onopen event is ac-
tivated. The anonymous function in our example writes the string online in green
into a status line at the end of the HTML document. For each message received
by the WebSocket, it activates the onmessage event. The data attribute of the vari-
able e available for this function contains the payload sent by the server. In our
example, the data is converted into a JavaScript object via JSON.parse, which
means that the server has to send a JSON string (details on this will follow later in
this section). If the conversion is unsuccessful, the function is terminated and an
appropriate error message appears on the HTML page.
A valid message contains a JavaScript object with user name (user), message text
(text) , and the color in which the message is to be displayed (color). As you can
see in Figure 9.1, each user is writing on his own line and in his own color. The
server assigns colors to users; assigning a new line is implemented on the cli-
ent. The subsequent if query checks if the last message is from the same user
as the previously received message. If that is the case, the innerHTML value of the
variable ele is assigned the received text. If it is a different user or this is the first
message, a new paragraph with the name ele is created and added to the div ele-
ment with the ID broadcast. The variable currentUser is then set to the value of
the current user:
if (currentUser == msg.user) {
ele.innerHTML = msg.text;
} else {
ele = document.createElement("p");
$("broadcast").appendChild(ele);
ele.style.color = msg.color;
ele.innerHTML = msg.text;
currentUser = msg.user;
}
};
};