Game Development Reference
In-Depth Information
The server-side code
A typical use case for web sockets is a multiplayer game where two or more players
either play against each other or otherwise share the same game, in real time, but
from different locations. One way such a game could be implemented (say, a fighting
game such as Street Fighter or Mortal Kombat) is by having two players connect-
ing to the server from separate computers, then the server would receive input from
both players and send them the output computed from their actions. Each player's
client application would then simply render the data received from the server. For ex-
ample, player A presses a key on the keyboard that makes the character controlled
by player A jump. That data is sent to the server, which is keeping track of where the
character is and whether it can jump, and so on. After the server computes what is
to be done based on the input it received from player A (in this example, the server
determines that player A's character is now performing a jump), it sends the updated
state of player A's character to both player A and player B. Their application then
simply renders player A's character up in the air. Of course, each player's local in-
stance of the game also renders the state it calculates from a local player's actions
in order to provide instant feedback. However, the server-side instance of the game
has the ability to invalidate any game state resulting from input from either player, if
it is determined to be invalid. This way, both players can experience a very smooth,
responsive multiplayer gaming experience, while the integrity of the game remains
in check.
Now, depending on the specific language in which the server-side code is implemen-
ted, this could either be a trivial task or a real nightmare. Overall, the main thing that
this server-side code needs to keep track of is all of the sockets connected to it. Ob-
viously, the complexity of the application will be relative to the goals of the game.
However, as far as the web sockets API is concerned, the main point is to pass
data back to the client using the send interface function and check on input from the
onMessage function.
The client-side code
As we saw in the previous code snippet, working with the JavaScript WebSocket ob-
ject is very straightforward. Two things to keep in mind, however, are that every call
to WebSocket.send is asynchronous and whatever data is padded to WebSock-
et.send must be (or will be converted to) a DOMString . That means that if we
Search WWH ::




Custom Search