242 Chapter 9—WebSockets
Before we can start digitalizing the ships, we need to find a partner so we can
play. This is done by selecting a player from the list of logged-in users and
clicking the button Invite Player to send that user an invitation to play. The
callback function of this button locates the player ID and sends an invitation
message to the WebSocket server:
this.invitePlayer = function() {
var opts = document.forms.loggedin.users.options;
if (opts.selectedIndex != -1) {
wsMessage({
task : 'private',
request : 'invite',
client : opts[opts.selectedIndex].value
});
}
};
The called function wsMessage() directs the message in JSON format to the serv-
er. It can also contain additional steps, such as checking the validity of the mes-
sage or similar steps:
var wsMessage = function(msg) {
game.websocket.send(JSON.stringify(msg));
};
The variable game in this code listing represents the central game object, and
contains all variables relevant to the game. On the server, the invitation is iden-
tified as a private message, the sender’s data is added, and then the message is
sent to the selected player.
With the server in game_server.js, it would look like this:
else if (msg.task == 'private') {
msg.from = USERS[conn.id];
conn.writeclient(JSON.stringify(msg),msg.client);
}
This user is presented with a little window asking to play a game with you (see
Figure 9.4). If the user declines, you receive the answer No thanks, not now; if
the user accepts, the user list is hidden and the digitalization component for
placing the ships is displayed. Let’s first look at the code for inviting someone
to play. On the client, we see it as part of the onmessage callback function for all
server messages:
game.websocket.onmessage = function(e) {
var msg = JSON.parse(e.data);
if (msg.request == 'invite') {
var frm = document.forms.inviteConfirm;