首页 > 解决方案 > 如何确保服务器使用 python - twisted 从客户端接收到完整数据(如果没有 - 重新发送)?

问题描述

我是扭曲和网络编程本身的新手。我想要的是实现服务器和客户端(并在它们之间传递一些字符串数据)。问题是,数据很重要,所以我希望客户端将其重新发送到服务器,以防连接丢失或服务器端未满。但是我不想重新发送它,以防它被完全接收,所以我不认为仅仅将逻辑添加到 def connectionLost() 就可以了。怎么可能做到这一点?

这是我的服务器(与文档示例中的相同)并且(在------------之后)是客户端:

from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class ConsoleReceiver(Protocol):

    def connectionMade(self):
        self.transport.write(
            "Welcome!\n".encode('utf-8'))

    def dataReceived(self, data):
        self.transport.write('Data received, thanks'.encode('utf-8'))
        data = data.decode('ascii')
        print(data)
        self.transport.loseConnection()

class ServerFactory(Factory):

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

if __name__ == '__main__':
    endpoint = TCP4ServerEndpoint(reactor, 21285)
    endpoint.listen(ServerFactory())
    reactor.run()``` 

-----------------------------------------------------------------------------


@some_flask_route.route('/test/')

    urgent_information = <getting some urgent information from db with flask_sqlalchemy>

    reactor.connectTCP('localhost', 21285, ShiftInfoSenderFactory(urgent_information))
    reactor.run()


class ShiftInfoSender(Protocol):
    def __init__(self, urgent_information):
        self.urgent_information = urgent_information

    def connectionMade(self):
        self.transport.write('\nInformation to be red:{}\n'.format(self.urgent_information[1]).encode('utf-8'))
        for i in self.urgent_information[2]:
            self.transport.write('Some unpacked information: {}'.format(i).encode('utf-8')

    def dataReceived(self, data):
        print(data.decode('ascii'))


class ShiftInfoSenderFactory(ClientFactory):
    def __init__(self, urgent_information):
        self.urgent_information = urgent_information

    def startedConnecting(self, connector):
        print('Started to connect')

    def buildProtocol(self, addr):
        print('Connected')
        return ShiftInfoSender(self.urgent_information)

    def clientConnectionLost(self, connector, reason):
        print('Lost connection. Reason:', reason)

    def clientConnectionFailed(self, connector, reason):
        print('Connection failed. Reason:', reason) ``` 




标签: pythontcpserverclienttwisted

解决方案


推荐阅读