from socket import * import os, thread from random import randint import fcntl from popen2 import Popen3 MESSAGE = """ WELCOME TO THE PUBLIC TUNNELHACK SERVER Support: bryce@lanset.com | 530-415-8436 (USA) p: Play TunnelHack s: view top scores w: Watch a game q: quit (Coming soon!) """ PORT = randint(10000,15000) print PORT s = socket(AF_INET, SOCK_STREAM) s.bind(("", PORT)) s.listen(5) def serve_client(con, adr): con.send(MESSAGE) while 1: # menu con.send("> "); command = con.recv(5) if command[0] == 'p': do_game(con, adr); return; elif command[0] == 'q': con.send("Goodbye.\n"); con.close() return; elif command[0] == 's': con.send("\t\t ---- Top Scores: ----\n") con.send(os.popen("head -n 30 scores.txt").read()) elif command[0] == 'w': con.send("This doesn't work yet, sorry."); def do_game(con, adr): pipe = Popen3("java Tunnels") ins, outs = pipe.tochild, pipe.fromchild#os.popen2("java Tunnels"); #print dir(ins), dir(outs) con.setblocking(0) fl = fcntl.fcntl(ins, fcntl.F_GETFL) fcntl.fcntl(outs, fcntl.F_SETFL, fl | os.O_NDELAY) ins.write(str(adr)+"\n") ins.flush() while 1: os.wait(1) if pipe.poll() != -1: break try: tx = con.recv(100) if tx: #print "To tunnels", tx ins.write(tx) ins.flush() except: pass try: st = outs.read() if st: #print "from tunnels", st con.send(st) except : pass con.send(os.popen("tail -n 6 scores.txt").read()) os.system("python sortscore.py 100") con.send("\nGoodbye!\n") con.close() while 1: con, adr = s.accept() thread.start_new_thread(serve_client, (con, adr))