Ping和Pong在一个线程化的WebSocket服务器(Python)中

时间:2011-12-08 17:13:19

标签: python sockets websocket ping

我使用lastest websocket spec在Python中编写了一个线程化的websocket服务器,我试图让它每隔x秒向每个客户端发送一个ping请求。我想出来的唯一方法是覆盖BaseServer.server_forever(),如下所示:

# 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()

这是构造Ping帧的函数,它只是将时间戳放在内容中:

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

运行此

时会发生不好的事情
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

我认为这归结于我对Python中的重写方式缺乏了解或者对这个问题采取根本错误的方法。有没有更好的方法来实现这个或使这个代码有效?

1 个答案:

答案 0 :(得分:3)

代码不会在任何地方设置属性__is_shut_down__shutdown_request。因此,尝试访问它们失败。在构造函数中创建它们,如下所示:

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()

响应更新:

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

表示另一个进程已绑定到指定的端口。在Unix上,您可以使用sudo netstat -ltpn找到该过程。或者,选择其他端口。