Game Development Reference
In-Depth Information
Whereas a web worker uses the
postMessage
function, a web socket uses the
send
function. The traditional event handling functions work the exact same way
as with workers. There are four events associated with a socket, namely
onOpen
,
onClose
,
onError
, and
onMessage
. The first two events,
onOpen
and
onClose
,
are called when the server successfully validates the request and upgrades the con-
nection with the browser and when the server somehow closes a connection with
the particular socket, respectively. The
onError
event is fired when an error occurs
on the server application. Finally, when the server pushes a message to the client,
the JavaScript handle to the socket is alerted through the
onMessage
callback func-
tion. The event object that is passed to the function, similar to a web worker
onMes-
sage
event object, has a
data
attribute with the actual data sent to it, as well as a
timestamp
attribute indicating when the message was sent.
The connection
Understanding the way a web application connects to a backend server through a
web socket is fundamental to learning how the socket API works. The first point to re-
member is that the protocol that connects the browser to the server is different from
the usual HTTP connection. The way a browser keeps the connection open with the
server is by using the new
WebSocket
protocol, which is done by following a few
steps. The
WebSocket
protocol is based on the traditional TCP and uses HTTP to
upgrade the connection between a browser and a backend server, as illustrated in
the following screenshot: