Game Development Reference
In-Depth Information
Web sockets
If you've ever thought about creating a high performance multiplayer game in HTML5
then the new web sockets API is just the thing you've been looking for. If you haven't
done much with socket programming before, this is what you've been missing: instead
of establishing a connection to a server each and every time a resource needs to be
requested, a socket simply creates a connection once, then the client and server can
communicate back and forth over that same connection. To put it another way, ima-
gine making a phone call to someone, saying "Hello", then hanging up the phone after
the other person says "Hello" back to you. Then, you call that person again, wait for
them to pick up the phone and once you're both ready, you ask the person on the oth-
er side of the line how he or she is doing. After receiving an answer, you again hang
up the phone. This continues for the duration of the conversation, where you only ask
a question at a time (or make a single statement at a time), and most of the time is
spent with both of you waiting for the call to come in and connecting the phones.
Now, with socket programming, the above scenario would be like making one phone
call, then having the entire conversation without ever hanging up the phone. The only
time you would hang up the phone would be when the conversation is finally over, and
you and the other person have said good bye, and agreed to put down the phone. In
this situation, there is virtually no delay between question and answer—only whatever
intrinsic delay is involved in the sound traveling from one phone to another.
In HTML5, the sockets API is divided into two parts, namely a server part and a client
part. The server side of the socket is something we will not discuss too much in this
topic, given the nature of what's involved. The client-side interface is where we will
spend most of the discussion, although you will be happy to know that the JavaScript
interface for web sockets and web workers is nearly identical.
// Step 1: Open connection
var con = new WebSocket
("ws://localhost:8888/packt/sockets/
multiplayer-game-server");
// Step 2: Register callbacks
con.addEventListener("open", doOnOpen);
con.addEventListener("error", doOnError);
Search WWH ::




Custom Search