0

I know that this is a duplicate Send multiple messages to server from twisted client, however the answers there don't really help and I still have questions on how to solve this issue.

To test, I wrote a simple echo server that just echos whatever message it receives back to the client, and for my client code I have:

class InsertRecord(Protocol):
    def __init__(self, message):
        print("Protocol initialized")
        self.msg = message
    def connectionMade(self):
        self.transport.write(self.msg)
    def sendMessage(self, msg):
        self.transport.write("MESSAGE %s\n" % msg)

    def dataReceived(self, data):
        print("data")
        reactor.stop()

class ClientInsertFactory(ClientFactory):
    def __init__(self, dataRecord):
        self.dataRecord = dataRecord
        print("Client factor init")
    def buildProtocol(self, addr):
        return InsertRecord(self.dataRecord)
    def startedConnecting(self, connector):
        print("Started to connect to IS Server")


reactor.connectTCP("localhost", 2222, ClientInsertFactory("message1"))
reactor.run()
connector = reactor.connectTCP("localhost", 2222, ClientInsertFactory("message2"))
reactor.run()

I know that I am unable to stop and restart the reactor, however, I can't think of a way to get around this. What I want is to be able to generate multiple sessions with the server without getting blocked by the call to reactor.run(). As per the post linked before, I want to be able have a way to be able to call sendData outside the protocol.

  • Can you be more specific about what you want? You've defined it by exclusion - "outside the protocol". That leaves ... an infinite number of other possibilities. Can you just edit your question to say what you want to do (instead of what you don't)? – Jean-Paul Calderone Dec 05 '17 at 12:05
  • What I want, as an example, is establish a client session with the server. In this session, the client will send one message to the server, and then end its session with the server, and run its client side code, when at some point, it wants to again establish another session with the server, and send some updated information. – Hanson Duan Dec 06 '17 at 03:47
  • Replace `reactor.stop()` with `self.transport.loseConnection()` to close the connection to the server. Don't stop the reactor unless your application has finished. – notorious.no Dec 07 '17 at 20:07

0 Answers0