Skip to content

Instantly share code, notes, and snippets.

@Inndy
Created June 21, 2015 07:07
Show Gist options
  • Select an option

  • Save Inndy/2cbe64b711a56f5aa9ec to your computer and use it in GitHub Desktop.

Select an option

Save Inndy/2cbe64b711a56f5aa9ec to your computer and use it in GitHub Desktop.
Write a program react with stdio, and use this program bind it onto tcp/ip socket.
#!/usr/bin/env python
import sys, socket, thread, subprocess
class ConnectionHandler:
def __init__(self, conn, remote, execute):
print("New Connection: " + str(remote))
f = conn.makefile('rb+', 0)
p = subprocess.Popen(execute, stdin = f, stdout = f)
p.wait()
conn.close()
def main(execute, host = '0.0.0.0', port = 8080, IPv6 = False, handler = ConnectionHandler):
if IPv6 == True:
soc_type = socket.AF_INET6
else:
soc_type = socket.AF_INET
soc = socket.socket(soc_type)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
soc.bind((host, port))
print("Serving on %s:%d."%(host, port))
soc.listen(0)
while 1:
try:
thread.start_new_thread(handler, soc.accept() + (execute, ))
except KeyboardInterrupt:
print("Exit Server")
soc.close()
exit()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: %s [port] exec [args]' % sys.argv[0])
exit()
elif len(sys.argv) == 2:
executable = sys.argv[1]
port = 8080
else:
try:
port = int(sys.argv[1])
executable = sys.argv[2:]
except ValueError:
port = 8080
executable = sys.argv[1:]
main(executable, port = port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment