HTML and CSS Reference
In-Depth Information
HTML5 WebSocket Technology and Pusher
We already talked a bit about WebSocket and realtime, but let's recap: HTML5 WebSocket allows applications to push
data to the client rather than requiring the client to constantly ask for new data.
eXerCISe 2-6: trYING OUt the WeBSOCKet apI
let's have a look at the native Websocket apI to get an idea of how it can be used. Create an htMl file with the
following content. this file contains Javascript that connects to a Websocket echo test service. this means that
you can test connecting, sending, and receiving messages.
<!doctype html>
<html lang="en">
<meta charset="utf-8" />
<title>Trying out the WebSocket API 02-06</title>
var ws = new WebSocket( 'ws://' );
ws.onopen = function() {
console.log( 'connected' );
console.log( '> hello' );
ws.send( 'hello' );
ws.onmessage = function( ev ) { console.log( '< ' + ); };
ws.onclose = function() { console.log( 'closed' ); };
ws.onerror = function() { console.log( 'error' ); };
If you open up this page in a browser that supports Websocket and open up the browser's Javascript console,
you'll see the following:
> hello
< hello
The connected message is displayed when WebSocket has connected to the server, and the onopen function
handler has been called. The code then logs > hello to indicate it's going to send hello over the WebSocket
connection to the server using the WebSocket send function. Finally, when the server echoes back the message, the
onmessage function handler is called, and < hello is logged to the console.
Search WWH ::

Custom Search