Skip to content

Instantly share code, notes, and snippets.

@yourbuddyconner
Created June 29, 2014 08:53
Show Gist options
  • Save yourbuddyconner/a457fea162e268606119 to your computer and use it in GitHub Desktop.
Save yourbuddyconner/a457fea162e268606119 to your computer and use it in GitHub Desktop.
Python server to listen to a TCP socket and dump traffic to a file, then serve that file via HTTP
# A simple script that creates two TCP sockets, one that listens
# for and handles HTTP traffic on port 9000 and one that
# listens for and handles vanilla TCP traffic on port 9001
# Web Server portion is set up to support Cross Origin Requests, FYI
import sys # for exit()
import BaseHTTPServer # for WebHandler
import SocketServer # for everything
import json # for json parsing
from thread import * # for threading
def main():
print 'Initializing . . .'
WSPORT = 9000
TCPPORT = 9002
HOST = '' # Symbolic name meaning all available interfaces
# Little webserver that listens on port 9000 and serves a couple json files
class WebHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Handler only returns two urls, everything else results in a 404.
"""
def do_OPTION(s):
print "WEB SERVER: Got an Option Request!"
s.send_response(200)
s.send_header("Access-Control-Allow-Origin", "*")
s.end_headers()
def do_GET(s):
"""Respond to a GET request."""
# serves our schedule.json file
# this should only change about once per day
print 'Web Server: Got a GET Request!'
if s.path == "/schedule.json":
s.send_response(200)
s.send_header("Content-type", "application/json")
s.send_header("Access-Control-Allow-Origin", "*")
s.end_headers()
# get the schedule from the file
schedule = open("schedule.json", "r")
# write the contents to the stream
s.wfile.write(schedule.read())
schedule.close()
return
# Serves the current playing track - This might get queried/changed
# a LOT, so it might be best to not keep a file and instead have
# the track be a variable or something
elif s.path == "/current_song.json":
s.send_response(200)
s.send_header("Content-type", "application/json")
s.end_headers()
return
# If it's not one of those two, return a 404 to the client
else:
s.send_response(404)
s.send_header("Content-type", "text/html")
s.send_header("Content-Length", "95")
s.send_header("Access-Control-Allow-Origin", "*")
s.end_headers()
s.wfile.write("<html>\n<body>\n<h1>File Not Found</h1>\n")
s.wfile.write("<p>We're too busy yoloing... Sorry...</p>\n</body>\n</html>")
return
return
# TCP Server - Listens on port 9001 and updates our json files based on the message content
class TCPHandler(SocketServer.BaseRequestHandler):
"""
TCP Handler, listens on port 9001 and waits for traffic. When traffic is
detected, a file is opened and the content is replaced with the text from
the message.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "TCP Server: {} wrote:".format(self.client_address[0])
print type(self.data)
try:
j = json.loads(self.data);
except ValueError:
print "TCP Server: Message rejected - Not JSON!"
pass
else:
current_file = open("schedule.json", "w")
json.dump(j, current_file)
print "TCP Server: Data from {} saved into {}".format(self.client_address[0], current_file.name)
current_file.close()
# just send back the same data, but upper-cased
self.request.sendall("Data Saved!\n")
httpd = SocketServer.TCPServer((HOST, WSPORT), WebHandler)
tcpd = SocketServer.TCPServer((HOST, TCPPORT), TCPHandler)
start_new_thread(httpd.serve_forever, ())
print 'Created Web Server thread listening at port: ', WSPORT
start_new_thread(tcpd.serve_forever, ())
print 'Created TCP Server thread listening at port: ', TCPPORT
try:
print 'Running forever. Ctrl+C to stop.'
while True:
continue
except KeyboardInterrupt:
pass
print
print "Keyboard Interrupt!! Shutting down..."
print
httpd.shutdown()
tcpd.shutdown()
sys.exit()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment