python - 如何在客户端关闭套接字之前保持套接字打开?

标签 python networking

我有简单的 python 服务器和客户端。

服务器:

import SocketServer
import threading


class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print str(self.client_address[0]) + " wrote: "
        print self.data
        self.request.send(self.data.upper())


if __name__ == "__main__":
    HOST, PORT = "localhost", 3288
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

客户:

import socket
import sys
from time import sleep

HOST, PORT = "localhost", 3288
data = "hello"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    sock.connect((HOST, PORT))
    sock.send(data + "\n")
    received = sock.recv(1024)

    sleep(10)

    sock.send(data + "\n")
    received = sock.recv(1024)

    sleep(10)

    sock.send(data + "\n")
    received = sock.recv(1024)

finally:
    sock.close()

这是我得到的输出:

服务器:

>python server.py
127.0.0.1 wrote:
hello

客户:

>python client.py
Traceback (most recent call last):
  File "client.py", line 18, in <module>
    received = sock.recv(1024)
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine

我也在 linux 机器上试过。服务器只收到一条消息,然后我在第二条消息的 recv 语句中收到错误。我刚开始在 python 上学习网络,但我认为服务器出于某种原因正在关闭套接字。我该如何纠正这个问题?

最佳答案

为每个连接创建一个MyTcpHandler对象,调用handle处理客户端。 handle 返回时连接关闭,因此您必须在 handle 方法中处理来自客户端的完整通信:

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while 1:
            self.data = self.request.recv(1024)
            if not self.data:
                break
            self.data = self.data.strip()
            print str(self.client_address[0]) + " wrote: "
            print self.data
            self.request.send(self.data.upper())

注意:当客户端关闭连接时,recv 返回 '',所以我在 recv 之后移动了 .strip() 所以不会因为客户端只发送空白而误报。

关于python - 如何在客户端关闭套接字之前保持套接字打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627986/

相关文章:

python - 找不到 Django sqlite 列错误

python - Jupyter 笔记本会发出错误警告

networking - 没有可选字段的 Protocol Buffer : Fixed size?

php - 如何找出接收到的udp数据包的数据大小

python - 将套接字与 wxpython 一起使用

python - 根据另一个的范围和类别填充 Pandas 列

python - 如何在 Python Pandas 数据框中每行下添加 24 行

java - 如何以编程方式将 IP 数据包字节写入 PCAP 文件格式?

networking - 能否让 Micrel KSZ8995 遵守 RFC 3927,以免泄露链接本地地址?

c++ - 将多个客户端连接到服务器的好方法是什么?