title: python websocket handshake (RFC 6455)
body: <p>I am trying to implement a simple websoket server on python, using RFC 6455 protocol.
  I took handshake format from <a href="http://en.wikipedia.org/wiki/WebSocket#WebSocket_protocol_handshake" rel="nofollow noreferrer">here</a> and <a href="https://www.rfc-editor.org/rfc/rfc6455#section-1.3" rel="nofollow noreferrer">here</a>.</p>
  <p>I am using Chromium 17 and Firefox 11 as clients, and getting this error:</p>
  <p><code>Uncaught Error: INVALID_STATE_ERR: DOM Exception 11</code></p>
  <p>I expect to see <code>hello from server</code> in my browser and <code>hello from client</code> in server log.</p>
  <p>I guess my handshake is wrong, can you point me to my mistake?</p>
  <p>##Server log, request:</p>
  <pre><code>GET / HTTP/1.1
  Upgrade: websocket
  Connection: Upgrade
  Host: 127.0.0.1:8999
  Origin: null
  Sec-WebSocket-Key: 8rYWWxsBPEigeGKDRNOndg==
  Sec-WebSocket-Version: 13
  </code></pre>
  <p>##Server log, response:</p>
  <pre><code>HTTP/1.1 101 Switching Protocols
  Upgrade: websocket
  Connection: Upgrade
  Sec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=
  </code></pre>
  <p>##Raw-string response:</p>
  <pre><code>HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=\r\n\r\n
  </code></pre>
  <p>##Server code:</p>
  <pre><code>import socket
  import re
  from base64 import b64encode
  from hashlib import sha1
  
  websocket_answer = (
      'HTTP/1.1 101 Switching Protocols',
      'Upgrade: websocket',
      'Connection: Upgrade',
      'Sec-WebSocket-Accept: {key}\r\n\r\n',
  )
  
  GUID = &quot;258EAFA5-E914-47DA-95CA-C5AB0DC85B11&quot;
  
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.bind(('127.0.0.1', 8999))
  s.listen(1)
  
  client, address = s.accept()
  text = client.recv(1024)
  print text
  
  key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text)
      .groups()[0]
      .strip())
  
  response_key = b64encode(sha1(key + GUID).digest())
  response = '\r\n'.join(websocket_answer).format(key=response_key)
  
  print response
  client.send(response)
  
  print client.recv(1024)
  client.send('hello from server')
  </code></pre>
  <p>##Client code:</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;test&lt;/title&gt;
      &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
      &lt;script type=&quot;text/javascript&quot;&gt;
          var s = new WebSocket('ws://127.0.0.1:8999');
          s.onmessage = function(t){alert(t)};
          s.send('hello from client');
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>