25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

156<br />

CHAPTER 6 ■ USING THE <strong>HTML</strong>5 WEBSOCKET API<br />

That’s it. Bi-directional browser communication made simple. For completeness, Listing 6-8 shows<br />

the entire <strong>HTML</strong> page with the WebSocket code.<br />

Listing 6-8. websocket.html code<br />

<br />

WebSocket Test Page<br />

<br />

var log = function(s) {<br />

if (document.readyState !== "complete") {<br />

log.buffer.push(s);<br />

} else {<br />

document.getElementById("output").inner<strong>HTML</strong> += (s + "\n");<br />

}<br />

}<br />

log.buffer = [];<br />

url = "ws://localhost:8080/echo";<br />

w = new WebSocket(url);<br />

w.onopen = function() {<br />

log("open");<br />

w.send("thank you for accepting this WebSocket request");<br />

}<br />

w.onmessage = function(e) {<br />

log(e.data);<br />

}<br />

w.onclose = function(e) {<br />

log("closed");<br />

}<br />

window.onload = function() {<br />

log(log.buffer.join("\n"));<br />

document.getElementById("sendButton").onclick = function() {<br />

w.send(document.getElementById("inputMessage").value);<br />

}<br />

}<br />

<br />

Send<br />

<br />

Running the WebSocket Page<br />

To test the websocket.html page that contains the WebSocket code, open a command prompt, navigate<br />

to the folder that contains the WebSocket code, and issue the following command to host the <strong>HTML</strong> file:<br />

python -m SimpleHTTPServer 9999

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!