title: Python example of Joe's Erlang websocket example
body: <p>I've just been working through the erlang websockets example from <a href="http://armstrongonsoftware.blogspot.com/2009/12/comet-is-dead-long-live-websockets.html" rel="nofollow noreferrer">Joe Armstrong's blog</a> I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some erlang by interpreting joe's code). I'm having two issues:</p>
  
  <p>1) Data I receive from the page includes a 'ÿ' as the last char. This doesn't appear in the erlang version and I can't work out where it's coming from <strong>Fixed - This was because the strings where encoded in utf-8 and I wasn't decoding them</strong></p>
  
  <p>2) I seem to be sending data from the server (through the websocket) - which can be confirmed by looking at how many bytes client.send() makes. But nothing is appearing on the page. <strong>Fixed, I wasn't encoding the string correctly</strong></p>
  
  <p>I've put all the code <a href="http://github.com/mattyw/PublicSandpit" rel="nofollow noreferrer">here</a>. Here's my python version incase i'm missing anything obvious</p>
  
  <pre><code>import threading
  import socket
  
  def start_server():
      tick = 0
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.bind(('localhost', 1234))
      sock.listen(100)
      while True:
          print 'listening...'
          csock, address = sock.accept()
          tick+=1
          print 'connection!' 
          handshake(csock, tick)
          print 'handshaken'
          while True:
              interact(csock, tick)
              tick+=1
  
  def handshake(client, tick):
      our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade:     WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin:     http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
      shake = client.recv(255)
      print shake
      client.send(our_handshake)
  
  def interact(client, tick):
      data = client.recv(255)
      print 'got:%s' %(data)
      client.send("clock ! tick%d\r" % (tick))
      client.send("out ! recv\r")
  
  if __name__ == '__main__':
      start_server()
  </code></pre>
  
  <p>For those who haven't run through joe's example but still want to help, you just need to serve up interact.html through a web server and then start your server (The code assumes the webserver is running on localhost:8888)</p>