Created
March 3, 2013 08:17
-
-
Save umbrant/5075297 to your computer and use it in GitHub Desktop.
Simple multi-threaded python server that offers up a file with a delay per line
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
import socket | |
import time | |
import threading | |
import SocketServer | |
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): | |
def handle(self): | |
data = open("file", "r").readlines() | |
for line in data: | |
self.request.send(line) | |
time.sleep(1) | |
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): | |
pass | |
if __name__ == "__main__": | |
# Port 0 means to select an arbitrary unused port | |
HOST, PORT = "localhost", 8083 | |
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) | |
ip, port = server.server_address | |
# Start a thread with the server -- that thread will then start one | |
# more thread for each request | |
server_thread = threading.Thread(target=server.serve_forever) | |
# Exit the server thread when the main thread terminates | |
server_thread.daemon = True | |
server_thread.start() | |
print "Server loop running in thread:", server_thread.name | |
while True: | |
pass | |
server.shutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment