Keeping the WebSocket connection alive

后端 未结 1 1475
天命终不由人
天命终不由人 2021-02-04 12:20

I\'m doing a study on WebSocket protocol and trying to implement a simple ECHO service for now with Python on the backend. It seems to work fine but the connection drops right a

1条回答
  •  清歌不尽
    2021-02-04 12:40

    The connection is closed each time after handle. You should rather stay there reading incoming data:

    # incoming connection
    def setup(self):
        print "connection established", self.client_address
    
    def handle(self):
        while 1:
            try:
                self.data = self.request.recv(1024).strip()
    
                # incoming message
                self.headers = self.headsToDict(self.data.split("\r\n"))
    
                # its a handshake
                if "Upgrade" in self.headers and self.headers["Upgrade"] == "websocket":
                    key = self.headers["Sec-WebSocket-Key"]
                    accept = b64encode(sha1(key + MAGIC).hexdigest().decode('hex'))
                    response = "HTTP/1.1 101 Switching Protocols\r\n"
                    response += "Upgrade: websocket\r\n"
                    response += "Connection: Upgrade\r\n"
                    response += "Sec-WebSocket-Accept: "+accept+"\r\n\r\n"
                    print response
                    self.request.send(response)
                # its a normal message, echo it back
                else:
                    print self.data
                    self.request.send(self.data)
            except:
                print "except"
                break
    

    0 讨论(0)
提交回复
热议问题