HTML5 Guidelines for Web Developers

(coco) #1
9.2 Example: A Broadcast Server 235

Figure 9.1 Four connections to the WebSocket broadcast server


9.2.1 The Broadcast Client


In the HTML code we just need a text field for entering the message to be sent. To
demonstrate the capabilities of WebSocket, we want every character to be sent
to all connected users immediately. To achieve this, we use the oninput event of
the text field and call the sendmsg() function for each keystroke, which we will
analyze later on:


Broadcast messages





The JavaScript section starts with a definition of the previously encountered $()
function, loaned from the jQuery library. As soon as the whole document is load-
ed, the WebSocket is initialized and assigned to the variable ws. In our example,
we use the server html5.komplett.cc on the special port 8887. The server is speci-
fied via a URL, and the protocol is abbreviated with ws://. Similar to the SSL
encoded HTTPS, there is also an encoded channel for WebSockets, called with
wss:// as the protocol. For our example, we stick with the uncoded variation.
The path specified in the URL (/bc) is not relevant for our WebSocket server, be-
cause the server on this port has the sole purpose of serving this example (more
about the server in section 9.2.2, The Broadcast Server):

Free download pdf