Skip to content

Instantly share code, notes, and snippets.

@d6e
Last active September 16, 2021 23:38
Show Gist options
  • Save d6e/d6a9430faa9d4307fe4140998eeffef4 to your computer and use it in GitHub Desktop.
Save d6e/d6a9430faa9d4307fe4140998eeffef4 to your computer and use it in GitHub Desktop.
A simple python tcp server which writes json data to file
import socket
import json
HOST = ""
PORT = 8888
def send_response(msg, code, code_msg, conn):
http_response = ("HTTP/1.1 {code} {code_msg}\n\n{msg}"
"".format(code=code, code_msg=code_msg, msg=msg))
client_connection.sendall(http_response)
client_connection.close()
if __name__ == "__main__":
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print "Running on port {}".format(PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print request
separator = '\r\n\r\n' # This is probably standard enough...?
if separator in request:
raw_data = request.split(separator)[1] # janky parsing
try:
json.loads(raw_data) # validate json data
except ValueError:
send_response("Go away", 400, "INVALID", client_connection)
else:
with open('output.txt', 'a') as f:
f.write('\n'+raw_data)
send_response("Success.", 200, "OK", client_connection)
else:
send_response("Go away", 400, "INVALID", client_connection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment