Skip to content

Instantly share code, notes, and snippets.

@pklaus
Created July 30, 2014 07:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pklaus/c4c37152e261a9e9331f to your computer and use it in GitHub Desktop.
Save pklaus/c4c37152e261a9e9331f to your computer and use it in GitHub Desktop.
TCP Server using socketserver in Python3
#!/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)
@rbatistacardoso
Copy link

Nice work. Thanks!

@bluearte
Copy link

Thank you for sharing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment