Usage¶
The following is a simple example of using the Twistless decorator to start a twisted reactor with stackless support.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | """
This example is based off of the echo server example from twisted matrix
documentation.
The original client will work fine and can be found here
http://twistedmatrix.com/documents/13.1.0/core/examples/simpleclient.py
"""
import time
from twistless import twistless, tasklet
from stackless import schedule
from twisted.internet import reactor, protocol
@tasklet
def async():
"""A deferred executed in another tasklet."""
#Schedule this function to be continued at a later time.
schedule()
#Do something lengthy
time.sleep(5)
print("Tasklets!")
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"""
As soon as any data is received, write it back ASAP. But first setup a
function to be called when there is time for it.
"""
#call the async deferred function in another tasklet
#The server will echo a response and then return to the tasklet
#schedule which has the async method waiting to be returned to.
async()
self.transport.write(data)
@twistless
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|