Skip to content

Instantly share code, notes, and snippets.

@ferstar
Created May 14, 2015 08:46
Show Gist options
  • Save ferstar/c112f6aeb9dd47727ac6 to your computer and use it in GitHub Desktop.
Save ferstar/c112f6aeb9dd47727ac6 to your computer and use it in GitHub Desktop.
simple JSON TCP server and client
#!/usr/bin/env python3
import socket
import json
HOST, PORT = "localhost", 9527
data = {
"name": "hello, I am Tom.",
"age": 10,
"info": "sample is simple."
}
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.send(bytes(json.dumps(data), 'UTF-8'))
# Receive data from the server and shut down
received = json.loads(sock.recv(1024).decode('UTF-8'))
finally:
sock.close()
print ("Sent: {}".format(data))
print ("Received: {}".format(received))
#!/usr/bin/env python3
import socketserver, subprocess, sys
from threading import Thread
from pprint import pprint
import json
HOST = 'localhost'
PORT = 9527
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))
for key in json.loads(text):
pprint(json.loads(text)[key])
self.request.send(bytes(json.dumps({"status":"success!"}), '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