def handshake(self): headers = {} shake = self.connection.recv(1024) print "%s \t \n" %(shake) if not len(shake): return False header, data = shake.split('\r\n\r\n', 1) for line in header.split("\r\n")[1:]: key, value = line.split(": ", 1) headers[key] = value if (headers.has_key("Sec-WebSocket-Key") == False): logger.debug("This socket is not Websocket,so close it!") self.connection.close() return False szOrigin = headers["Origin"] szKey = base64.b64encode( hashlib.sha1(headers["Sec-WebSocket-Key"] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) szHost = headers["Host"] our_handshake = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade:websocket\r\n" \ "Connection: Upgrade\r\n" \ "Sec-WebSocket-Accept:" + szKey + "\r\n" \ "WebSocket-Origin:" + szOrigin + "\r\n" \ "WebSocket-Location: ws://" + szHost + "/WebManagerSocket\r\n" \ "WebSocket-Protocol:WebManagerSocket\r\n\r\n" self.connection.send(our_handshake) return True
def init_socket(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.bind((self.host, self.port)) # 绑定本地地址,端口self.port sock.listen(100) except Exception, e: logger.debug("[WebSocketInit] %s \t \n" % (e)) sys.exit()