python - TCP 服务器正在关闭连接

标签 python

我有这个代码

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        _data = self.request.recv(1024)

        Utils.log("Received from %s: %s" % (self.client_address, _data))

调用它

kamcon_server = ThreadedTCPServer((HOST, 3011), ThreadedTCPRequestHandler)

server_thread = threading.Thread(target = kamcon_server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()

我可以连接到主机,服务器可以发送数据,但是当客户端向服务器发送东西时,连接会自动关闭。为什么?谢谢。

最佳答案

您的handle() 方法每个连接只调用一次recv()。如果要处理来自客户端的多个消息,则需要循环。您还应该考虑您的协议(protocol),以便您可以处理大于 1024 字节的请求/响应消息(例如,解析 _data 并确定您是否有完整的消息、缓冲部分请求等)。

例如:

def handle(self):
    close = 0
    while not close:
        _data = self.request.recv(1024)
        if not _data:
            # EOF, client closed, just return
            return
        Utils.log("Received from %s: %s" % (self.client_address, _data))
        self.request.send('got %d bytes\r\n' % len(_data))
        if 'quit' in _data:
            close = 1

客户端 session :

% telnet localhost 3011
hi
got 4 bytes
bye
got 5 bytes
telnet> quit

关于python - TCP 服务器正在关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5793252/

相关文章:

python - 在 asyncio add_done_callback 回调中访问上下文变量

python - 属性错误 : 'NoneType' object has no attribute 'sendline' yet module contains the attribute having tested it another way?

python - 仅删除特定位置的逗号

python - 通过后缀组合列表元素

python - 如何使 django 测试框架从实时数据库读取?

python - Python 中用于大数的 Sigmoid 函数

python - Pillow 安装错误 : command 'gcc' failed with exit status 1

python - 将数组中的某些元素相乘

python - Tensorflow - 矩阵中点的欧几里德距离

python - 如何在python中逐列对两个矩阵进行线性卷积