How to send data manually using twisted

此生再无相见时 提交于 2021-01-28 00:47:40

问题


I'm new to twisted framework.

And I know there are many callback function will trigger automatically

When the connection made or lost.

But I have no idea how to send the data without those callbacks.

For example , I want to put an method custom_write() for sending the data out.

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

And trigger the function in my main(): method.

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

by the reactor.custom_write("HAHAHA")

And what if I create multiple reactor binding in different port.

Eg: localhost:1234, localhsot:5678

and send the different two messages to the 2 connections.

Eg: "Thanks" to port 1234 , Bye~ to port 5678

Any information can give me.

Thanks

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

回答1:


You can call connectTCP() more than once and using different hosts, ports. connectTCP() returns immediately without waiting for the full exchange to complete. To send different strings, you could pass them into the factories that can make them available to protocols.



来源:https://stackoverflow.com/questions/20396649/how-to-send-data-manually-using-twisted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!