Python: SocketServer 意外关闭 TCP 连接

Python: SocketServer closes TCP connection unexpectedly

我想实现一个 TCP/IP 网络客户端应用程序,将请求发送到 Python SocketServer and expects responses in return. I have started out with the official Python SocketServer sample code:

server.py:

#!/usr/bin/env python
# encoding: utf-8

import SocketServer

class MyTCPHandler(SocketServer.StreamRequestHandler):

    def handle(self):
        request  = self.rfile.readline().strip()
        print "RX [%s]: %s" % (self.client_address[0], request)

        response = self.processRequest(request)

        print "TX [%s]: %s" % (self.client_address[0], response)
        self.wfile.write(response)

    def processRequest(self, message):
        if   message == 'request type 01':
            return 'response type 01'
        elif message == 'request type 02':
            return 'response type 02'

if __name__ == "__main__":
    server = SocketServer.TCPServer(('localhost', 12345), MyTCPHandler)
    server.serve_forever()

client.py:

#!/usr/bin/env python
# encoding: utf-8

import socket

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

try:
    sock.connect(('127.0.0.1', 12345))

    data = 'request type 01'
    sent = sock.sendall(data + '\n')
    if sent == 0:
        raise RuntimeError("socket connection broken")

    received = sock.recv(1024)
    print "Sent:     {}".format(data)
    print "Received: {}".format(received)

    data = 'request type 02'
    sent = sock.sendall(data + '\n')
    if sent == 0:
        raise RuntimeError("socket connection broken")

    received = sock.recv(1024)
    print "Sent:     {}".format(data)
    print "Received: {}".format(received)

except Exception as e:
    print e

finally:
    sock.close()

server.py 输出:

RX [127.0.0.1]: request type 01
TX [127.0.0.1]: response type 01

client.py 输出:

Sent:     request type 01
Received: response type 01
[Errno 54] Connection reset by peer

哪里做错了?似乎服务器正在关闭连接。我怎样才能让它保持打开状态?

注意:这是

的后续问题

更新(在之后):

我从中得到的是 SocketServer.StreamRequestHandler 不是最新的设计,虽然它允许我通过网络连接,但它并不能真正支持我所有 TCP/IP -我需要注意的相关方面以实现稳健的通信。

这已在 Python 3 中通过 asyncio, but as the project lives in Python 2, that's not an option. I have therefore implemented the server and client described above in Twisted:

解决

server.py:

#!/usr/bin/env python
# encoding: utf-8

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class SimpleProtocol(LineReceiver):

    def connectionMade(self):
        print 'connectionMade'

    # NOTE: lineReceived(...) doesn't seem to get called

    def dataReceived(self, data):
        print 'dataReceived'
        print 'RX: %s' % data

        if   data == 'request type 01':
            response = 'response type 01'
        elif data == 'request type 02':
            response = 'response type 02'
        else:
            response = 'unsupported request'

        print 'TX: %s' % response
        self.sendLine(response)

class SimpleProtocolFactory(Factory):

    def buildProtocol(self, addr):
        return SimpleProtocol()

reactor.listenTCP(12345, SimpleProtocolFactory(), interface='127.0.0.1')
reactor.run()

client.py:

#!/usr/bin/env python
# encoding: utf-8

from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol

class SimpleClientProtocol(Protocol):
    def sendMessage(self, msg):
        print "[TX]: %s" % msg
        self.transport.write(msg)

def gotProtocol(p):
    p.sendMessage('request type 01')
    reactor.callLater(1, p.sendMessage, 'request type 02')
    reactor.callLater(2, p.transport.loseConnection)

point = TCP4ClientEndpoint(reactor, '127.0.0.1', 12345)
d = connectProtocol(point, SimpleClientProtocol())
d.addCallback(gotProtocol)
reactor.run()

客户端没有关闭,而是一直空闲到 CTRL+C。 Twisted 可能需要一段时间才能让我明白,但对于手头的工作来说,使用经过测试和尝试的框架显然比自己完成所有这些基础工作更合理。

注意: 这在 Twisted XmlStream: How to connect to events?

处继续

客户端坏了。它只调用 recv 一次,然后关闭连接而不确保它已收到服务器必须发送的所有内容。

解决此问题的正确方法取决于您使用的协议,您尚未解释。从服务器代码中看不出服务器到客户端 "messages" 的协议是什么。客户端应该期望从服务器得到什么?例如,服务器期望来自客户端的 line,一条标有换行符以指示行尾的消息。所以服务器通过检查换行符知道它何时收到消息。客户应该怎么做?该代码在哪里?

为了论证,我假设您的协议始终使用消息并将消息定义为由换行符终止。

    request  = self.rfile.readline().strip()

这会读取 消息 因为它调用 readline.

sent = sock.sendall(data + '\n')

这会发送一条 消息,因为它会发送一系列由换行符终止的字节。

received = sock.recv(1024)

糟糕,这只是接收了一些字节,而不是消息。需要有代码来检查是否收到换行符,如果没有收到,则再次调用 recv,否则调用 close 将强制异常关闭套接字(因为消息没有,并且可以永远不会,收到),这正是你所看到的。

这里的问题是,在 TCPHandler 中,"request" 实际上是一个完整的连接,从头到尾。* 您的处理程序在 accept 上被调用,当您return 套接字由此关闭。

如果你想在此之上构建一个请求-响应-协议处理程序,它在单个套接字级请求上处理多个协议级请求,你必须自己做(或使用更高级别的框架)。 (像 BaseHTTPServer 这样的子类演示了如何做到这一点。)

例如,您可以只在 handle 函数中使用循环。当然你可能想在这里添加一个异常处理程序 and/or 处理来自 rfile 的 EOF(注意 self.rfile.readline() 将 return '' 用于 EOF,但是 '\n' 一个空行,所以你必须在调用 strip 之前检查它,除非你想让一个空行在你的协议中表示 "quit" )。例如:

def handle(self):
    try:
        while True:
            request  = self.rfile.readline()
            if not request:
                break
            request = request.rstrip()
            print "RX [%s]: %s" % (self.client_address[0], request)

            response = self.processRequest(request)

            print "TX [%s]: %s" % (self.client_address[0], response)
            self.wfile.write(response + '\n')
    except Exception as e:
        print "ER [%s]: %r" % (self.client_address[0], e)
    print "DC [%s]: disconnected" % (self.client_address[0])

这将 经常 与您现有的客户端一起工作,至少在卸载机器上的本地主机上,但它实际上并不正确,而且 "often works" 很少足够好。请参阅 TCP sockets are byte streams, not message streams for a longer discussion, but briefly, you also need to do the stuff mentioned in : append newlines to what you write from the server (which I already did above), and have the client read line by line instead of just trying to read 1024 bytes at a time (which you can do by writing your own buffer-and-split-lines code, or just by using the makefile 方法,因此它可以像服务器端一样使用 rfile.readline()。)

不修复客户端不会导致回答索赔的问题,但导致这样的问题:

Sent:     request type 01
Received: resp
Sent:     request type 02
Received: onse type 01
response typ

而且您可以看到,在实际尝试以编程方式处理响应的真实程序中,像 response type 01\nresponse typ 这样的响应不会很有用......


* 注意 SocketServer 是一个没有人真正喜欢的古老设计。 Python 3 添加 asyncio, and that people in Python 2 usually use third-party frameworks like Twisted and gevent 是有原因的。它们对于简单任务来说更简单,对于复杂任务来说更 flexible/powerful(并且效率更高)。