9.2 Example: A Broadcast Server 237
function sendmsg() {
ws.send($("ta").value);
}
ws.onclose = function(e){
$("status").innerHTML = 'offline';
$("status").style.color = 'red';
};
window.onunload = function(){
ws.close();
};
The sendmsg() function fired with every keystroke within the text field sends the
entire content of the text field to the WebSocket.
If the connection to the WebSocket is terminated for any reason (for example,
due to an absent network connection or server problems), the WebSocket object
fires the close event and consequently the onclose function. In our example, we
set the status line to offline in red. When leaving the site (window.onunload), we
explicitly close the WebSocket, logging out of the server.
9.2.2 The Broadcast Server
To complete the example, we still need the server component. As mentioned
earlier, we use the node.js runtime and the node-websocket-server for the Web-
Socket examples in this book. This makes sense didactically because we do not
need to switch to another programming language. After all, the server code is
meant to be easily understandable for you as well.
Similar to the client, the server works based on events. Each established connec-
tion and each received message fires a connection or message event, respectively,
to which we react in the JavaScript code. At the beginning of the script, we load
the node-websocket-server library, located in the directory lib/ under the name
ws.js. A new WebSocket object is assigned to the variable server:
var ws = require(__dirname + '/lib/ws'),
server = ws.createServer();
var user_cols = {};
server.addListener("connection", function(conn) {
var h = conn._server.manager.length*70;
user_cols[conn.id] = "hsl("+h+",100%,30%)";
var msg = {};
msg.user = conn.id;
msg.color = user_cols[conn.id];
msg.text = "A new user has entered the chat";
conn.broadcast(JSON.stringify(msg));