Created
July 30, 2014 07:51
-
-
Save pklaus/c4c37152e261a9e9331f to your computer and use it in GitHub Desktop.
TCP Server using socketserver in Python3
This file contains hidden or 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 | |
# skeleton from http://kmkeen.com/socketserver/2009-04-03-13-45-57-003.html | |
import socketserver, subprocess, sys | |
from threading import Thread | |
from pprint import pprint | |
import json | |
my_unix_command = ['bc'] | |
HOST = 'localhost' | |
PORT = 2000 | |
class SingleTCPHandler(socketserver.BaseRequestHandler): | |
"One instance per connection. Override handle(self) to customize action." | |
def handle(self): | |
# self.request is the client connection | |
data = self.request.recv(1024) # clip input at 1Kb | |
text = data.decode('utf-8') | |
pprint(json.loads(text)) | |
self.request.send('OK'.encode('utf-8')) | |
self.request.close() | |
class SimpleServer(socketserver.ThreadingMixIn, socketserver.TCPServer): | |
# Ctrl-C will cleanly kill all spawned threads | |
daemon_threads = True | |
# much faster rebinding | |
allow_reuse_address = True | |
def __init__(self, server_address, RequestHandlerClass): | |
socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) | |
if __name__ == "__main__": | |
server = SimpleServer((HOST, PORT), SingleTCPHandler) | |
# terminate with Ctrl-C | |
try: | |
server.serve_forever() | |
except KeyboardInterrupt: | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work. Thanks!