Python: SocketServer неожиданно закрывает TCP-соединение
Я хотел бы реализовать клиентское приложение сети TCP / IP, которое отправляет запросы на PythonSocketServer и ожидает ответов в ответ. Я начал с официального PythonПример кода SocketServer:
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
Что я делаю не так? Кажется, сервер закрывает соединение. Как я могу сделать его открытым?
Примечание: это дополнительный вопрос кC ++ / Qt: QTcpSocket не будет писать после чтения
Обновление (послеответ Абарнерта):
Что я убираю из этого, так этоSocketServer.StreamRequestHandler
это не самая последняя разработка, и хотя она позволяет мне подключаться по сети, на самом деле она не поддерживает меня со всеми аспектами, связанными с TCP / IP, о которых мне нужно позаботиться, чтобы реализовать надежную связь.
Это было решено в Python 3 сasyncio, но так как проект живет в Python 2, это не вариант. Поэтому я реализовал сервер и клиент, описанные выше вскрученный:
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 XmlStream: как подключиться к событиям?