简体   繁体   中英

Ping and Pong in a threaded WebSocket server (Python)

I've written a threaded websocket server in Python, using the lastest websocket spec and I'm trying to make it send a ping request to every client every x seconds. The only way I came up with to do this is overriding BaseServer.server_forever() like this:

# override BaseServer's serve_forever to send a ping request every now and then
class ModTCPServer(SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
        self.__is_shut_down = threading.Event()
        self.__shutdown_request = False

    def serve_forever(self, poll_interval=0.5):
        ###
        global PING_EVERY_SEC
        self.lastPing = int(time())
        ###
        self.__is_shut_down.clear()
        try:
            while not self.__shutdown_request:
                r, w, e = select.select([self], [], [], poll_interval)
                if self in r:
                    self._handle_request_noblock()
                ###
                now = int(time())
                if (now - self.lastPing) >= PING_EVERY_SEC:
                    self.socket.send(WebSocketPing(['0x89','0x21','0xa7','0x4b'], now)) # arbitrary key
                    self.lastPing = now
                ###
        finally:
            self.__shutdown_request = False
            self.__is_shut_down.set()

class LoginServer(SocketServer.ThreadingMixIn, ModTCPServer):
    pass

server = LoginServer(("", PORT), ApplicationHandler)
print "serving at port", PORT

server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

while server_thread.isAlive():
    pass

server.shutdown()

Here is the function that constructs the Ping frame, it just puts the timestamp in the contents:

def WebSocketPing(key, timestamp=False):
    data = ['0x89','0x8a'] # 0x89 = fin,ping 0x8a = masked,len=10
    data.extend(key)
    if timestamp:
        t = str(timestamp)
    else:
        t = str(int(time()))
    for i in range(10):
        masking_byte = int(key[i%4],16)
        masked = ord(t[i])
        data.append(hex(masked ^ masking_byte))
    frame = ''
    for i in range(len(data)):
        frame += chr(int(data[i],16))
    return frame

Bad things happen when I run this

Traceback (most recent call last):
  File "LoginServer.py", line 91, in <module>
    server = LoginServer(("", PORT), ApplicationHandler)
  File "LoginServer.py", line 63, in __init__
    SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
  File "/usr/lib/python2.6/SocketServer.py", line 400, in __init__
    self.server_bind()
  File "/usr/lib/python2.6/SocketServer.py", line 411, in server_bind
    self.socket.bind(self.server_address)
  File "<string>", line 1, in bind
socket.error: [Errno 112] Address already in use

I assume this is down to my lack of understanding of how overriding works in Python or to a fundamentally wrong approach to this problem. Is there a better way to do this or a way to make this code work?

The codes does not set the properties __is_shut_down and __shutdown_request anywhere. Therefore, trying to access them fails. Create them in the constructor, like this:

class ModTCPServer(SocketServer.TCPServer):
    def __init__(self, *args, **kwargs):
        SocketServer.TCPServer.__init__(self, *args, **kwargs)
        self.__is_shut_down = threading.Event()
        self.__shutdown_request = threading.Event()

In response to the update:

socket.error: [Errno 112] Address already in use

means that another process has already bound to the specified port. On Unix, you can find that process with sudo netstat -ltpn . Alternatively, choose a different port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM