Python:SocketServer没有套接字

标签 python sockets python-3.x socketserver

我想使用Python套接字服务器来等待消息,但定期超时并进行一些其他处理。据我所知,下面的代码应该可以工作,但是对handle_request()的调用会抛出一个AttributeError异常,提示MyTCPServer对象没有属性“socket”。我做错了什么?

import socketserver

class SingleTCPHandler(socketserver.BaseRequestHandler):
    # One instance per connection.  Override handle(self) to customize action.
    def handle(self):
        # self.request is the client connection
        data = self.request.recv(1024)  # clip input at 1Kb
        print ("Received data: " + data.decode())
        self.request.close()

class MyTCPServer(socketserver.BaseServer):

    def __init__(self, serverAddress, handler):
        super().__init__(serverAddress, handler)

    def handle_timeout(self):
        print ("No message received in {0} seconds".format(self.timeout))

if __name__ == "__main__":
    print ("SocketServerWithTimeout.py")
    tcpServer = MyTCPServer(("127.0.0.1", 5006), SingleTCPHandler)
    tcpServer.timeout = 5

    loopCount = 0
    while loopCount < 5:
        tcpServer.handle_request()
        print ("Back from handle_request")
        loopCount = loopCount + 1

最佳答案

socketserver.BaseServer 是 UDP 和 TCP 服务器的公共(public)基类。

如果您的服务器继承自 socketserver.TCPServer,您的代码将正常工作。

关于Python:SocketServer没有套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34665639/

相关文章:

使用pygame处理Python矩形碰撞

java - Spring RestTemplate SocketException 连接在快速连续执行时重置

java - readLine() 循环在远程客户端关闭连接之前不会退出

python-3.x - 使用部署的 Azure 函数从 Blob 存储下载文件非常慢

python - 无法从 JSON 对象在 Python 中打印字符 '\u2019'

javascript - 将 ajax 响应传递给 django 模板

Python - 尝试从包含字符串列表的列创建二进制特征

python - 如何在 Numpy 中就地扩展数组?

ios - Secure Transport TLS 应该如何与 Swift 中的 BSD 套接字一起使用?

python - helpers.scan() 不滚动 - ElasticSearch