Game Development Reference
In-Depth Information
});
});
});
On the clientMessage event, the handler first retrieves the username variable.
In case username cannot be retrieved, it sets socket.id as the username variable.
Then, it creates a new JSON object message and assigns username, room name,
and received JSON object to the message property. It emits serverMessage to the
emitting client as well as all users in the room, as shown in the following code:
socket.on('clientMessage', function(content) {
socket.get('username', function(err, username) { if (! username)
{
username = socket.id;
}
socket.get('room', function(err, room) {
if (err) {
throw err;
}
var broadcast = socket.broadcast;
if (room) {
broadcast.to(room);
}
var message={};
message.username=username;
message.roomname=room;
message.message=JSON.parse(content);
broadcast.emit('serverMessage', JSON.stringify(message));
message.username="you";
socket.emit('serverMessage', JSON.stringify(message)); });
});
});
});
The client code
Now, we will walk through the client code. Open 10-Multiple-Player-
Programming.html from the client folder in your editor. The client code connects
to the server on the page load. This following code is present in this file:
<script type="text/javascript">
var socket = io.connect('http://127.0.0.1');
 
Search WWH ::




Custom Search