All notes


<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
  var wsUri = "ws://";
  var output;

  function init()
    output = document.getElementById("output");

  function testWebSocket()
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };

  function onOpen(evt)
    doSend("WebSocket rocks");

  function onClose(evt)

  function onMessage(evt)
    writeToScreen('<span style="color: blue;">RESPONSE: ' +'</span>');

  function onError(evt)
    writeToScreen('<span style="color: red;">ERROR:</span> ' +;

  function doSend(message)
    writeToScreen("SENT: " + message); 

  function writeToScreen(message)
    var pre = document.createElement("p"); = "break-word";
    pre.innerHTML = message;

  window.addEventListener("load", init, false);

<h2>WebSocket Test</h2>
<div id="output"></div>



Used to replace the unscalable polling and long-polling solutions that were used to simulate a full-duplex connection by maintaining two connections.

The browser sends a request to the server, indicating that it wants to switch protocols from HTTP to WebSocket, through the Upgrade header:

GET ws:// HTTP/1.1
Cookie: __utma=99as
Connection: Upgrade
Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==
Upgrade: websocket
Sec-WebSocket-Version: 13

If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.

HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: Upgrade
Server: Kaazing Gateway
Upgrade: WebSocket
Access-Control-Allow-Credentials: true
Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=
Access-Control-Allow-Headers: content-type
At this point the HTTP connection breaks down and is replaced by the WebSocket connection over the same underlying TCP/IP connection. The WebSocket connection uses the same ports as HTTP (80) and HTTPS (443), by default.

Once established, WebSocket data frames can be sent back and forth between the client and the server in full-duplex mode. Both text and binary frames can be sent in either direction at the same time.

The data is minimally framed with just two bytes (start byte and end byte): In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. WebSocket text frames use a terminator, while binary frames use a length prefix.