Game Development Reference
In-Depth Information
Understanding events and the code flow
In the preceding section, we have described the data that we need to transfer and
in this section, we will list the custom events that we will emit for the preceding
communication and also list the reserved events. We describe in the form of an
algorithm for both the client and server sides. The sequence defines the event
flow from the server to the client and vice versa. The following steps are basic
initialization steps. They describe the sequence from the user connect request until
the user room join event:
The server creates a client socket and emits a login event using the following
line of code:
socket.emit('login');
The client handles .on('login',handler) and emits the server login
custom event and sends its username using the following line of code:
socket.emit('login', "player");
The server handles .on('login',handler) , saves the username in private
user data and sends the client the confirmation that the user has logged
in by emitting the loggedIn event. It broadcasts the event with the actual
username to all clients and emits with the username you to the emitting
client, using the following lines of code:
socket.broadcast.emit('loggedIn', JSON.stringify(message));
message.username="you";
socket.emit('loggedIn', JSON.stringify(message));
The client handles the loggedIn custom event. In our code, we are not listing
all users but we can use it to create a list of connected users. In our case, if
the emitted username is you , then the socket emits the join event to join the
ourgame room, using the following line of code:
socket.emit('join', "ourgame");
The server handles the join event by adding the emitting socket to the room
using the following line of code:
socket.join(room);
Then, it emits the emitting socket and the roomJoined event to all users in
the room by using the following line of code:
socket.emit('roomJoined', JSON.stringify(message));
socket.broadcast.to(room).emit('roomJoined',
JSON.stringify(message));
 
Search WWH ::




Custom Search