【问题标题】:How to send data manually using twisted如何使用twisted手动发送数据
【发布时间】:2013-12-22 04:41:58
【问题描述】:

我是扭曲框架的新手。

而且我知道有很多回调函数会自动触发

连接建立或断开的时间。

但我不知道如何在没有这些回调的情况下发送数据。

例如,我想把一个方法custom_write() 用于发送数据。

    def custom_write(self,data):
        self.transport.write(
            data)

并在我的main(): 方法中触发函数。

def main():
    try:
        p_red("I'm Client")
        f = EchoFactory()
        reactor.connectTCP("localhost",
                            8000,
                            f)

reactor.custom_write("HAHAHA")

如果我在不同的端口创建多个反应器绑定会怎样。

Eg: localhost:1234, localhsot:5678

并将不同的两条消息发送到 2 个连接。

例如:"Thanks" to port 1234Bye~ to port 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

【问题讨论】:

  • 不要抓到BaseException。您可能希望允许 KeyboardInterrupt、SystemExit。

标签: python tcp twisted


【解决方案1】:

您可以多次调用connectTCP() 并使用不同的主机、端口。 connectTCP() 立即返回,无需等待完整交换完成。要发送不同的字符串,您可以将它们传递给可以使它们可用于协议的工厂。

【讨论】:

  • 嗯,但我只能调用 reactor.run() 一次.....为了更新我要发送的新报价或字符串,我建立了一个新连接,然后我需要运行反应器。运行()还是??
  • @sqp_125:通常,您只运行一次reactor.run()。其余的以异步方式发生。为了使代码看起来是同步的(可能更熟悉),您可以运行 task.react(main, sys.argv[1:]) 代替。比如看Mail Client on the Twisted home page注:connectTCP是比较低级的,看simpler clients would work in your case是否
猜你喜欢
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多