238 Chapter 9—WebSockets
The first event handler (connection) handles the new connections. As in Chap-
ter 8 in the section 8.5, Example: Click to tick!, we assign the color for the user
step by step in HSL, jumping ahead for each new user by 70 degrees (the num-
ber of users can be retrieved via the array conn._server.manager). The colors are
saved in the variable user_cols with the connection ID (conn.id) as an index. The
variable msg is furnished with the created color and the notification that a new
user has entered; then it is sent as a JSON string via the method conn.broadcast.
This method is a function of the node-websocket-server and broadcasts messag-
es to all clients except the one who fired the current event, which is exactly what
we want in this case: All users are informed that a new user has entered the chat:
conn.addListener("message", function(message) {
var msg = {};
message = message.replace(/</g, "<");
message = message.replace(/>/g, ">");
msg.text = message;
msg.user = conn.id;
msg.color = user_cols[conn.id];
conn.write(JSON.stringify(msg));
conn.broadcast(JSON.stringify(msg));
});
});
The second function reacting to the message event replaces the start and end
characters for HTML tags in the passed string (message) to ensure that no script
code or similar tricks can be smuggled in. A reliable application would have to
check input even more thoroughly to protect against possible attacks. After all,
the message is broadcast to all clients and displayed in their browsers, a nearly
ideal attack scenario. As in the connection event, a local variable msg is filled with
the desired content and sent as a JSON string. But here, it happens twice: first
with the write() method to the actual user and then with the broadcast()meth-
od to all other users.
The WebSocket server is almost finished. We are still missing an event handler
for closed connections and the actual start of the server:
server.addListener("close", function(conn) {
var msg = {};
msg.user = conn.id;
msg.color = user_cols[conn.id];
msg.text = "<em>A user has left the chat</em>";
conn.broadcast(JSON.stringify(msg));
});
server.listen(8887);