python - Twisted 服务器/客户端之间的多个调用/响应消息
问题描述
我有一个用 Twisted 实现的基本服务器和客户端。我的目标是让客户端处理一些数据,将其进度报告回服务器,然后重复直到处理完所有数据。客户端能够向服务器发送初始消息,但它没有收到服务器的响应,让它知道可以开始处理该数据。这是我的代码。
服务器:
from twisted.internet import reactor, protocol
PORT = 9000
progress = 0
class MyServer(protocol.Protocol):
def dataReceived(self, data):
global progress
print(data)
if data != "Ready?":
progress = int(data)
self.transport.write("Got it.")
self.transport.loseConnection()
def connectionLost(self, reason):
global progress
if progress == 10:
print("Completed.")
reactor.stop()
class MyServerFactory(protocol.Factory):
protocol = MyServer
factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()
客户:
from twisted.internet import reactor, protocol
import time
HOST = 'localhost'
PORT = 9000
progress = 0
class MyClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("Ready?")
self.transport.loseConnection()
def dataReceived(self, data):
global progress
progress += 1
print(progress)
self.transport.write(str(progress))
self.loseConnection()
def connectionLost(self, reason):
global progress
if progress == 10:
print("Completed.")
reactor.stop()
class MyClientFactory(protocol.ClientFactory):
protocol = MyClient
factory = MyClientFactory()
reactor.connectTCP(HOST, PORT, factory)
reactor.run()
解决方案
我发现我的问题是我过早地关闭了连接。在一些早期的测试中,我试图在dataReceived
函数中发送多条消息,这些消息被连接成一条消息。这使我相信您必须断开每条消息的连接才能通过。相反,您只需要在发送另一条消息之前让函数完成。这是按预期工作的更新代码。
服务器:
from twisted.internet import reactor, protocol
PORT = 9000
progress = 0
class MyServer(protocol.Protocol):
def dataReceived(self, data):
global progress
print(data)
if data != "Ready?":
progress = int(data)
self.transport.write("Got it")
if progress == 10:
self.transport.loseConnection()
def connectionLost(self, reason):
print("Completed.")
reactor.stop()
class MyServerFactory(protocol.Factory):
protocol = MyServer
factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()
客户:
from twisted.internet import reactor, protocol
import time
HOST = 'localhost'
PORT = 9000
progress = 0
class MyClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("Ready?")
def dataReceived(self, data):
global progress
progress += 1
print(progress)
self.transport.write(str(progress))
if progress == 10:
self.transport.loseConnection()
def connectionLost(self, reason):
print("Completed.")
reactor.stop()
class MyClientFactory(protocol.ClientFactory):
protocol = MyClient
factory = MyClientFactory()
reactor.connectTCP(HOST, PORT, factory)
reactor.run()
推荐阅读
- .net-core - 对“位图”类型的引用声称它在“System.Drawing”中定义,但找不到
- html - 显示带有下拉菜单的图像(在表格中)(无 javascript)
- java - Java,从具有 FireStore 数据的 Map 获取密钥
- python - 在 Python 中使用 Selenium 导航并使用 BeautifulSoup 进行抓取
- r - 在日期列标题上使用 melt()
- python - 一个作者和多个读者的`bytearray`线程安全吗?
- android-studio - 在 Android Studio 上访问 API 网关
- php - 序列化器 virtualProperty 和访问器有什么区别?
- python - 用简单的例子学习正则表达式
- java - 不可读的 Pom 文件 - Maven