Python 如何使用twisted手动发送数据
我不熟悉twisted框架 我知道有很多回调函数会自动触发 当连接建立或丢失时 但是我不知道如何在没有这些回调的情况下发送数据 例如,我想放置一个方法Python 如何使用twisted手动发送数据,python,tcp,twisted,Python,Tcp,Twisted,我不熟悉twisted框架 我知道有很多回调函数会自动触发 当连接建立或丢失时 但是我不知道如何在没有这些回调的情况下发送数据 例如,我想放置一个方法custom\u write(),用于发送数据 def custom_write(self,data): self.transport.write( data) 并触发mymain():方法中的函数 def main(): try: p_red("I'm Client")
custom\u write()
,用于发送数据
def custom_write(self,data):
self.transport.write(
data)
并触发mymain():
方法中的函数
def main():
try:
p_red("I'm Client")
f = EchoFactory()
reactor.connectTCP("localhost",
8000,
f)
通过reactor.custom_-write(“哈哈哈”)
如果我在不同的端口创建多个反应器绑定呢
Eg:localhost:1234,localhsot:5678
并将两条不同的消息发送到2个连接
例如:“感谢”端口1234
,再见~端口5678
任何信息都可以给我
谢谢
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write(
"I'm cli")
def custom_write(self,data):
self.transport.write(
data)
def dataReceived(self, data):
print "Server said:", data
self.transport.loseConnection()
pass
def connectionLost(self, reason):
print("[{0}] Lose connection...".format(
self.__class__.__name__)
)
pass
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
"""docstring for EchoFactory"""
def clientConnectionFailed(self,
connector,
reason):
print "[{0}] Connection failed - goodbye".format(
self.__class__.__name__)
reactor.stop()
def clientConnectionLost(self,
connector,
reason):
print "[{0}] Connection lost - goodbye".format(
self.__class__.__name__)
reactor.stop()
def main():
try:
p_red("I'm Client")
f = EchoFactory()
reactor.connectTCP("localhost",
8000,
f)
try:
reactor.run()
except BaseException as e:
traceback.print_exc(file=sys.stdout)
raise e
pass
except BaseException as e:
traceback.print_exc(file=sys.stdout)
raise e
pass
您可以使用不同的主机、端口多次调用
connectTCP()connectTCP()
立即返回,无需等待完全交换完成。要发送不同的字符串,您可以将它们传递到工厂,使它们可用于协议。不要捕获BaseException
。您可能希望允许KeyboardInterrupt,SystemExit.Hm,但我只能调用reactor.run()一次。。。。。为了更新我想要发送的新引号或字符串,我建立了一个新连接,然后我需要运行reactor.run()或???@sqp_125:通常,您只运行一次reactor.run()
。其余部分以异步方式进行。为了使代码看起来像是同步的(可能更熟悉),您可以运行task.react(main,sys.argv[1:])
。例如,请参见备注:connectTCP
的级别相对较低,请参见