Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

HTML5 and Web Sockets

Web sockets are one of the most technically advanced additions to HTML5, and they also have the potential to afford the most dramatic change to the way Internet work is done.

Long before the Web as we know it, programmers were using an idea called sockets to allow remote computers to communicate with a persistent connection. If you've ever used a Telnet, FTP, or SSH client, you've used a program that uses sockets. Typically, the programmer builds two types of sockets: One that lives on the server (a — wait for it — server socket) and one that lives on the client (you guessed it — a client socket.) These two programs communicate by a predetermined stylized communication agreement, called a communications protocol. In fact, Telnet, FTP, HTTP, and many other Internet tools are really more protocols than software. A Telnet program is actually a multipurpose socket client, and it can be used to test many different kinds of server sockets. The Web server itself is a specialized server that mainly speaks HTTP protocol, and the Web browser is a specialized client that speaks HTTP.

You can use a socket tool like Telnet to connect to an HTTP server. To test this, run the following code from the command line. (It should work the same on all major platforms: They all have a basic Telnet program built in.)

telnet aharrisbooks.net 80

You've connected to the server using port 80 (the standard Web server port). You'll see a response that looks like the following. (Boldface indicates that this comes from the server.)

Trying 66.40.52.176...
Connected to www.aharrisbooks.net.
Escape character is '^]'.

Now the server thinks you're a browser. To get a particular page, you need to send the same request the browser would send. To get the index for JavaScript and AJAX For Dummies by Andy Harris, use this request:

GET /jad/index.html HTTP/1.1
host: www.aharrisbooks.net

Press the Enter key twice after the last line to submit the request. You'll see a long string of HTML code — all the code that makes up the page. Of course, you'll see only the code because this isn't a real browser. At the end, you'll see this line:

Connection closed by foreign host.

This always happens because HTTP is a stateless protocol.

Web sockets provide an additional protocol. You can still connect to the Web page in the normal way, but when you implement a Web socket, you write code in your Web page that can connect to a server socket and communicate with it. While the page itself still uses the stateless HTTP protocol, the socket connection remains in place as long as the page is active, allowing for complete two-way communication without re-establishing a connection.

The type of connection you get with this mechanism is ideal for applications that require a great deal of client-server communication, such as chat applications and multiplayer games.

Of course, to build a Web socket connection, you need to have both a client and a server. Typically, the server is written in a language like PHP or Python. You also need knowledge of both socket programming and the language the server is built with to build a server socket. Many modern languages support a generic socket mode that can be used to create a specialized Web socket.

The code for a program that allows the user to input information, which is sent to the server and echoed back is somewhat long but not terribly complicated:

<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>WebSocket Test</title>
  <meta charset = "UTF-8" />
  <style type = "text/css">
  h1 {
    text-align: center;
  }
  .error {
    color: red;
  } 
  .response {
    color: blue;
  }
  fieldset {
    width: 80%;
    margin: auto;
    text-align: center;
    -moz-box-shadow: 10px 10px 10px #000000;
    -webkit-box-shadow: 10px 10px 10px #000000;
  }
  #output {
    font-family: monospace;
    width: 80%;
    margin-left: auto;
    margin-right: auto;
    margin-top: 1em;
    background-color: #eeeeee;
    padding: 1em;
    border: 5px groove #cccccc;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    -moz-box-shadow: 10px 10px 10px #000000;
    -webkit-box-shadow: 10px 10px 10px #000000;
  } 
  </style>
  <script language="javascript" type="text/javascript">
  var output;
  var websocket;
  function init(){
    output = document.getElementById("output");
  } // end init
  function connect(){
    //open socket
    if ("WebSocket" in window){
      websocket = new WebSocket("ws://echo.websocket.org/");
      //note this server does nothing but echo what was passed
      //use a more elaborate server for more interesting behavior
  
      output.innerHTML = "connecting..." ;
  
      //attach event handlers
      websocket.onopen = onOpen;
      websocket.onclose = onClose;
      websocket.onmessage = onMessage;
      websocket.onerror = onError;
    } else {
      alert("WebSockets not supported on your browser.");
    } // end if
  } // end connect
  function onOpen(evt){
    //called as soon as a connection is opened
    output.innerHTML = "<p>CONNECTED TO SERVER</p>";
  } // end onOpen
  function onClose(evt){
    //called when connection is severed
    output.innerHTML += "<p>DISCONNECTED</p>";
  } // end onClose;
  function onMessage(evt){
    //called on receipt of message
    output.innerHTML += "<p class = 'response'>RESPONSE: " 
      + evt.data + "</p>";
  } // end onMessage
  function onError(evt){
    //called on error
    output.innerHTML += "<p class = 'error'>ERROR: " 
      + evt.data + "</p>";
  } // end onError
  function sendMessage(){
    //get message from text field
    txtMessage = document.getElementById("txtMessage");
    message = txtMessage.value;
    //pass message to server
    websocket.send(message);
    output.innerHTML += "<p>MESSAGE SENT: " + message + "</p>";
  } // end sendMessage
  
  </script>
</head>
<body onload = "init()">
  <h1>Web Socket Echo Chamber</h1>
  <form action = "">
    <fieldset>
      <button type = "button"
              onclick = "connect()">
        connect to server
      </button>
      <label for = "txtMessage">
        <input type = "text"
               id = "txtMessage"
               value = "HTML5 Quick Reference For Dummies" />
      </label>
      <button type = "button"
              onclick = "sendMessage()">
        send message
      </button>
      <button type = "button"
              onclick = "websocket.close()">
        disconnect
      </button>
    </fieldset>
  </form>
  <div id="output">Click 'connect' button to connect</div>
</body>
</html>
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement
Learning anything is easy with For Dummies eLearning!

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!