Ejemplo n.º 1
0
    def connect(self, serv_addr):
        """
        Override connect to implement websocket handshake.
        """
        Connection.connect(self, serv_addr)

        # WebSocket Handshake
        request_headers = messages.make_ws_request_headers(serv_addr)
        self._ws_key = request_headers["sec-websocket-key"]
        request_data = messages.make_http_request('GET', '/',
                                                  headers=request_headers)

        self._sock.send(request_data)
        data = self._sock.recv(1024)            
        msg, data = messages.http_parse(data)
        if msg == None:
            self._sock.close()
            self._sock = None
            self._is_connected = False
            return

        response_headers, body = msg
        # Verify handshake response
        verified = messages.verify_ws_response_headers(self._ws_key, 
                                                       response_headers) 
        if verified:
            self._is_connected = True
        else:
            self._is_connected = False
            self._sock.close()
            self._sock = None

        return self._is_connected
Ejemplo n.º 2
0
 def _wait_response(self, sock, wait=1.0):
     """
     Wait maximum delta seconds for a single http response on socket
     This is run by a thread.
     """
     try:
         timeout = time.time() + wait
         recv_data = ''
         while not self._stop_event.is_set():
             remaining = min(timeout-time.time(), 1.0)
             if remaining <= 0:
                 break
             r,w,e = select.select([sock], [], [sock], remaining)
             if sock in r:
                 data = sock.recv(1024)
                 if data:
                     recv_data += data
                     payload, recv_data = messages.http_parse(recv_data)
                     if payload:
                         # completely read
                         return payload
                     else:
                         # not completely read yet
                         continue
                 else:
                     # readable yet no data
                     print "hello"
                     break
             elif sock in e:
                 print "errro"
             else:
                 # not readable yet (early timeout)
                 continue
     except (select.error, socket.error) as e:
         traceback.print_exc()
     finally:
         sock.close()