Created
March 1, 2011 18:56
-
-
Save hlian/849648 to your computer and use it in GitHub Desktop.
echoservermult.py implemented with SocketServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from sys import argv, exit | |
import threading | |
import SocketServer | |
HOST = 'localhost' | |
#----------------------------------------------------------------------- | |
class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): | |
def handle(self): | |
tid = str(threading.currentThread()) | |
print 'Spawned thread ' + tid | |
# FILE-esque wrappers have already been created by the | |
# StreamRequestHandler base class and are placed in self.rfile | |
# and self.wfile. | |
while True: | |
line = self.rfile.readline() | |
if not line: | |
break | |
self.wfile.write('Echo: ' + line) | |
self.wfile.flush() | |
# StreamRequestHandler takes care of closing the file objects. | |
print 'Exiting thread ' + tid | |
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): | |
pass | |
#----------------------------------------------------------------------- | |
def main(argv): | |
if len(argv) != 2: | |
print 'Usage: python %s port' % argv[0] | |
exit(1) | |
try: | |
port = int(argv[1]) | |
server = ThreadedTCPServer((HOST, port), ThreadedTCPRequestHandler) | |
print 'Starting server' | |
# The equivalent of the while-True loop in the original code. | |
server.serve_forever() | |
except Exception, e: | |
print e | |
#----------------------------------------------------------------------- | |
if __name__ == '__main__': | |
main(argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment