Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>All methods in twisted are <em>asynchronous</em>. All of the the methods such as <code>connectionMade</code> and <code>lineReceived</code> are happening on the same thread. The Twisted reactor runs a loop (called an <em>event loop</em>) and it calls methods such as <code>connectionMade</code> and <code>lineReceived</code> when these events happen.</p> <p>You have an infinite loop in <code>connectionMade</code>. Once Python gets into that loop, it can never get out. Twisted calls <code>connectionMade</code> when connection is established, and your code stays there forever. Twisted has no opportunity to actually write the data to the transport, or receive data, it is stuck in <code>connectionMade</code>!</p> <p>When you write Twisted code, the important point that you must understand is that you may not <em>block</em> on the Twisted thread. For example, let's say I want to send a "Hello" 4 seconds after a client connects. I might write this:</p> <pre><code>class EchoClient(LineReceiver): def connectionMade(self): time.sleep(4) self.transport.write("Hello") </code></pre> <p>but this would be wrong. What happens if 2 clients connect at the same time? The first client will go into <code>connectionMade</code>, and my program will hang for 4 seconds until the "Hello" is sent.</p> <p>The Twisted way to do this would be like this:</p> <pre><code>class EchoClient(LineReceiver): def connectionMade(self): reactor.callLater(4, self.sendHello) def sendHello(self): self.transport.write("Hello") </code></pre> <p>Now, when Twisted enters <code>connectionMade</code>, it calls <code>reactor.callLater</code> to <em>schedule</em> an event 4 seconds in the future. Then it exits <code>connectionMade</code> and continues doing all the other stuff it needs to do. Until you grasp the concept of async programming you can't continue in Twisted. I suggest you read through the <a href="https://twistedmatrix.com/documents/current/core/howto/index.html" rel="nofollow">Twisted docs here</a>.</p> <p>Finally, an unrelated note: If you have a <code>LineReceiver</code>, you should not implement your own <code>dataReceived</code>, it will make <code>lineReceived</code> not called. <code>LineReceiver</code> is a protocol which implements its own <code>dataReceived</code> which buffers and breaks up data into lines and calls <code>lineReceived</code> methods.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload