HTML and CSS Reference
In-Depth Information
Chapter 21
Going Real Time
What's in This Chapter?
• Understanding WebSockets
• Creating a WebSocket-enabled server with Socket.io
• Building a real-time multiplayer game
Wrox.com Code Downloads for This Chapter
You can find the wrox.com code downloads for this chapter at www.wrox.com/rem-
title.cgi?isbn=9781118301326 on the Download Code tab. The code is in the Chapter 21 download and individu-
ally named according to the names throughout the chapter.
Introduction
As shown in the preceding chapter, you can use a standard HTTP architecture to build multiplayer social games.
There are some limits, however, to what type of game you can build without resorting to various hacks if you want
the server to push data to the client. WebSockets provides a solution to this problem by bringing a socket-based,
real-time, two-way conversation mechanism natively to the browser. This chapter examines building real-time
games using a Node.js library named Socket.io, which supports WebSockets and a number of fallback mechan-
isms.
Understanding WebSockets
WebSockets provide a browser-native API that enables the creation of a socket connection to a server that
provides a real-time, bidirectional channel with which to pass messages in both directions: client to server and
server to client.
TCP sockets are a familiar concept in network programming; all HTTP traffic over the web is transported via
sockets. The problem from an HTML5 gaming perspective is that the browser opens a socket to the server, makes
an HTTP request for a resource, waits for it to finish downloading, and then closes the socket. After the socket
closes, sending any additional data requires opening a new socket. Furthermore, if the server has something to
tell the client, it needs to wait until the client requests a new resource before it can send data.
Prior to WebSockets, one solution that saw a fair amount of usage is long polling. Long polling means that
the client opens a request to the server that the server cannot write data to and instead remains open until it has
something to tell the client. After it has data for the client, it writes data to the socket and then closes it, treating
Search WWH ::




Custom Search