def startServerLoop(self): install(0) try: self.startServerLoopInner() finally: self.info('Server loop about to exit.') uninstall()
def startClientLoop(self): install(0) try: self.startClientLoopInner() finally: self.info('Client loop about to exit.') uninstall()
def startServerLoop(self): try: install(0) except StandardError: pass try: self.startServerLoopInner() finally: self.info('Server loop about to exit.') uninstall()
import stackless if __name__ == "__main__": currentPath = sys.path[0] parentPath = os.path.dirname(currentPath) if parentPath not in sys.path: sys.path.append(parentPath) # Insist on a local version of 'stacklesssocket.py'. stacklesssocketPath = os.path.join(currentPath, "stacklesssocket.py") if not os.path.exists(stacklesssocketPath): print "The unit tests require 'stacklesssocket.py' to be present in the 'examples' directory" sys.exit() import stacklesssocket stacklesssocket.install() import socket from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR import rpc SERVER_HOST = "127.0.0.1" SERVER_PORT = 40404 def Run(): def ConnectClientAndMakeCalls(): server = Server(SERVER_HOST, SERVER_PORT) clientSocket = socket.socket(AF_INET, SOCK_STREAM) clientSocket.connect((SERVER_HOST, SERVER_PORT))
# This code was written to serve as an example of Stackless Python usage. # Feel free to email me with any questions, comments, or suggestions for # improvement. # # But a better place to discuss Stackless Python related matters is the # mailing list: # # http://www.tismer.com/mailman/listinfo/stackless # # Monkeypatch in the stacklesssocket module. import sys, time import stackless import stacklesssocket #sys.modules["socket"] = stacklesssocket stacklesssocket.install() from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer body = """ <html> <head> <title>StacklessHTTPServer page</title> </head> <body> Nothing to see here, move along.. </body> </html> """ delays = [ 20, 5 ]
import urllib import stackless as SL import socket from stacklesssocket import install from iocp import install install() import re total = [0] def download( ): print "start" F = urllib.urlopen("http://www.163.com") return buf = F.read() print buf ma = re.findall('"(http://\w+\.163.com/[^"]+)', buf) for count, e in enumerate(ma): SL.tasklet(downurl)(e, count) SL.schedule() if count > 400: break print len(buf) def downurl( url, n ): print "start", n, url F = urllib.urlopen(url) buf = F.read() total[0]+=1
def Run(): global bootstrapState logging.basicConfig( level=logging.DEBUG, format='%(asctime)s;%(name)s;%(levelname)s;%(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger().name = "default" logging.getLogger("namespace").setLevel(logging.INFO) logging.getLogger("reloader").setLevel(logging.INFO) stackless.getcurrent().block_trap = True iniFilename = os.path.join(dirPath, "config.ini") if not os.path.exists(iniFilename): print "Please copy 'config.ini.base' to 'config.ini' and modify it appropriately." sys.exit(0) # Monkey-patch in the stackless-compatible sockets. import stacklesssocket import uthread2 import stacklesslib.main as stacklesslibmain stacklesssocket._schedule_func = lambda delay=0: stacklesslibmain.sleep( delay) stacklesssocket._sleep_func = stacklesslibmain.sleep stacklesssocket.install() # Install the global event handler. import __builtin__ from events import EventHandler __builtin__.events = EventHandler() # Add the "livecoding" contrib directory to the path. livecodingDirPath = os.path.join(dirPath, "contrib", "livecoding") if os.path.exists(livecodingDirPath): sys.path.append(livecodingDirPath) # Register the mudlib and game script directories with the livecoding # module. This will compile and execute them all. import reloader #gamePath = os.path.join("games", "room - simple") gamePath = os.path.join("games", "roguelike") gameScriptPath = os.path.join(dirPath, gamePath) mudlibScriptPath = os.path.join(dirPath, "mudlib") cr = reloader.CodeReloader() # Register for code reloading updates of managed classes. # Broadcast an event when we receive an update. cr.SetClassCreationCallback(OnClassCreation) cr.SetClassUpdateCallback(OnClassUpdate) cr.SetValidateScriptCallback(OnScriptValidation) cr.AddDirectory("mudlib", mudlibScriptPath) cr.AddDirectory("game", gameScriptPath) import imp __builtin__.sorrows = imp.new_module('sorrows') from mudlib.services import ServiceService svcSvc = ServiceService() svcSvc.gameScriptPath = gamePath svcSvc.gameDataPath = os.path.join(gamePath, "data") svcSvc.Register() svcSvc.Start() del svcSvc stackless.getcurrent().block_trap = False bootstrapState = STATE_RUNNING manualShutdown = False try: stacklesslibmain.mainloop.run() except KeyboardInterrupt: print print '** EXITING: Server manually stopping.' print if stackless.runcount > 1: print "Scheduled tasklets:", stackless.runcount uthread2.PrintTaskletChain(stackless.current) print if False: for entry in stacklesslibmain.event_queue.queue_a: print "Sleeping tasklets:" uthread2.PrintTaskletChain(uthread.yieldChannel.queue) print for timestamp, channel in uthread.sleepingTasklets: if channel.queue: print "Sleep channel (%d) tasklets:" % id(channel) uthread2.PrintTaskletChain(channel.queue) print manualShutdown = True finally: cr.EndMonitoring() bootstrapState = STATE_SHUTDOWN if manualShutdown: class HelperClass: def ShutdownComplete(self): stacklesslibmain.mainloop.stop() managerTasklet.kill() helper = HelperClass() events.ShutdownComplete.Register(helper.ShutdownComplete) stackless.tasklet(sorrows.services.Stop)() # We have most likely killed the stacklesssocket tasklet. managerTasklet = stacklesssocket.StartManager() stacklesslibmain.mainloop.run() logging.info("Shutdown complete")
def Run(): global bootstrapState logging.basicConfig( level=logging.DEBUG, format='%(asctime)s;%(name)s;%(levelname)s;%(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger().name = "default" logging.getLogger("namespace").setLevel(logging.INFO) logging.getLogger("reloader").setLevel(logging.INFO) stackless.getcurrent().block_trap = True iniFilename = os.path.join(dirPath, "config.ini") if not os.path.exists(iniFilename): print "Please copy 'config.ini.base' to 'config.ini' and modify it appropriately." sys.exit(0) # Monkey-patch in the stackless-compatible sockets. import stacklesssocket import uthread2 import stacklesslib.main as stacklesslibmain stacklesssocket._schedule_func = lambda delay=0: stacklesslibmain.sleep(delay) stacklesssocket._sleep_func = stacklesslibmain.sleep stacklesssocket.install() # Install the global event handler. import __builtin__ from events import EventHandler __builtin__.events = EventHandler() # Add the "livecoding" contrib directory to the path. livecodingDirPath = os.path.join(dirPath, "contrib", "livecoding") if os.path.exists(livecodingDirPath): sys.path.append(livecodingDirPath) # Register the mudlib and game script directories with the livecoding # module. This will compile and execute them all. import reloader #gamePath = os.path.join("games", "room - simple") gamePath = os.path.join("games", "roguelike") gameScriptPath = os.path.join(dirPath, gamePath) mudlibScriptPath = os.path.join(dirPath, "mudlib") cr = reloader.CodeReloader() # Register for code reloading updates of managed classes. # Broadcast an event when we receive an update. cr.SetClassCreationCallback(OnClassCreation) cr.SetClassUpdateCallback(OnClassUpdate) cr.SetValidateScriptCallback(OnScriptValidation) cr.AddDirectory("mudlib", mudlibScriptPath) cr.AddDirectory("game", gameScriptPath) import imp __builtin__.sorrows = imp.new_module('sorrows') from mudlib.services import ServiceService svcSvc = ServiceService() svcSvc.gameScriptPath = gamePath svcSvc.gameDataPath = os.path.join(gamePath, "data") svcSvc.Register() svcSvc.Start() del svcSvc stackless.getcurrent().block_trap = False bootstrapState = STATE_RUNNING manualShutdown = False try: stacklesslibmain.mainloop.run() except KeyboardInterrupt: print print '** EXITING: Server manually stopping.' print if stackless.runcount > 1: print "Scheduled tasklets:", stackless.runcount uthread2.PrintTaskletChain(stackless.current) print if False: for entry in stacklesslibmain.event_queue.queue_a: print "Sleeping tasklets:" uthread2.PrintTaskletChain(uthread.yieldChannel.queue) print for timestamp, channel in uthread.sleepingTasklets: if channel.queue: print "Sleep channel (%d) tasklets:" % id(channel) uthread2.PrintTaskletChain(channel.queue) print manualShutdown = True finally: cr.EndMonitoring() bootstrapState = STATE_SHUTDOWN if manualShutdown: class HelperClass: def ShutdownComplete(self): stacklesslibmain.mainloop.stop() managerTasklet.kill() helper = HelperClass() events.ShutdownComplete.Register(helper.ShutdownComplete) stackless.tasklet(sorrows.services.Stop)() # We have most likely killed the stacklesssocket tasklet. managerTasklet = stacklesssocket.StartManager() stacklesslibmain.mainloop.run() logging.info("Shutdown complete")