python - 如何确保服务器使用 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) ```
解决方案
推荐阅读
- php - 使用 PHP CURL 的 HTTP 请求并从邮递员和 curl cli 获得不同的结果
- javascript - 为什么我的简单 for 循环不能按我的意愿工作?
- python - `TypeError: 'float' 对象在尝试生成随机数时不能被解释为整数
- swift - 尝试使用 Firestore API 时出现 Swift 错误
- dart - Flutter 重定向到登录页面给出了“ancestorWidgetOfExactType”在 null 上被调用
- sql - Oracle查询以显示具有先前状态的每一行中的状态变化
- flutter - Flutter 模糊图像边缘不受影响(仅限 iOS)
- php - 将 php 循环数据附加到 JSON 对象
- python - pybind 创建的 *.so 文件与常规 linux 动态库之间的区别
- python - 为目录中所有文件的特定列 python 取每一行的正弦值