python – 如何保持套接字打开,直到客户端关闭?

我有简单的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方法中处理客户端的完整通信:

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 – 如何保持套接字打开,直到客户端关闭? - 代码日志