title: Creating a WebSocket Client in Python
body: <p>I am trying to learn about socket programming as well as the WebSocket protocol. I know that there are python web socket clients in existence but I am hoping to just build a toy version for my own learning. To do this I have created an extremely simple Tornado websocket server that I am running on <code>localhost:8888</code>. All it does is print a message when a client connects.</p>
  
  <p>This is the entire server - and it works (I have tested it with a small javascript script in my browser)</p>
  
  <pre><code>import tornado.httpserver
  import tornado.websocket
  import tornado.ioloop
  import tornado.web
  
  
  class WSHandler(tornado.websocket.WebSocketHandler):
      def open(self):
          print('new connection')
          self.write_message("Hello World")
  
      def on_message(self, message):
          print('message received %s' % message)
  
      def on_close(self):
        print('connection closed')
  
  application = tornado.web.Application([
      (r'/ws', WSHandler),
  ])
  
  
  if __name__ == "__main__":
      http_server = tornado.httpserver.HTTPServer(application)
      http_server.listen(8888)
      tornado.ioloop.IOLoop.instance().start()
  </code></pre>
  
  <p>So once I start up the server I try to run the following script</p>
  
  <pre><code>import socket
  
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect((socket.gethostbyname('localhost'), 8888))
  
  msg = '''GET /chat HTTP/1.1
  Host: server.example.com
  Upgrade: websocket
  Connection: Upgrade
  Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
  Origin: http://example.com
  Sec-WebSocket-Protocol: chat, superchat
  Sec-WebSocket-Version: 13'''.encode('ascii')
  print(len(msg))
  
  sent_count = sock.send(msg)
  print('sent this many bytes:', sent_count)
  recv_value = sock.recv(1)
  print('recvieved:', recv_value)
  </code></pre>
  
  <p>What I am hoping is that the server will send back the response header as specified in the RFC. Instead the sock.recv is hanging. This leads me to believe the server isn't acknowledging the websocket initial handshake. This handshake is pulled off of the RFC as well. I know that the websocket key should be random and everything, but I don't think that would cause the server to ignore the handshake (the websocket key is valid). I think I can figure the rest out once I can initiate the handshake so I am hoping that there is just some misunderstanding in either how websockets work or how to send the initial handhake.</p>