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 it like a normal request. The client processes the data sent from the server and then opens a new request immediately to wait for more data. This mechanism enables the server to send data to the client; however, the overhead associated with creating a new socket for each piece of data pushed in either direction means that performance suffers.

Flash ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.