Making dedicated match making server
[progcomp2013.git] / qchess / src / server.py
1 def dedicated_server():
2         max_games = 4
3         games = []
4         while True:
5                 # Get players
6                 s = socket.socket()
7                 s.bind(("0.0.0.0", 4562))
8                 s.listen(2)
9                 ss = s.accept()
10                 
11                 debug("Got white player")
12                 
13                 g = subprocess.Popen(["python", "qchess.py", "@network::"+str(4700+len(games)), "@network::"+str(4700+len(games)), "--log="+"_".join(str(datetime.datetime.now()).split(" ")) + ".log"], stdout=subprocess.PIPE)
14                 games.append(g)
15                 
16                 ss[0].send("white " + str(4700 + len(games)-1))
17                 ss[0].shutdown(socket.SHUT_RDWR)
18                 ss[0].close()
19                 
20                 time.sleep(0.5)
21                 ss = s.accept()
22                 
23                 debug("Got black player")
24                 
25                 ss[0].send("black " + str(4700 + len(games)-1))
26                 ss[0].shutdown(socket.SHUT_RDWR)
27                 ss[0].close()
28                 
29                 s.shutdown(socket.SHUT_RDWR)
30                 s.close()
31                 
32                 while len(games) > max_games:
33                         ready = select.select(map(lambda e : e.stdout, games),[], [], None)
34                         for r in ready:
35                                 s = r.readline().strip(" \r\n").split(" ")
36                                 if s[0] == "white" or s[0] == "black":
37                                         for g in games[:]:
38                                                 if g.stdout == r:
39                                                         games.remove(g)
40         
41 def client(addr):
42         
43         s = socket.socket()
44         s.connect((addr, 4562))
45         
46         [colour,port] = s.recv(1024).strip(" \r\n").split(" ")
47         
48         debug("Colour: " + colour + ", port: " + port)
49         
50         s.shutdown(socket.SHUT_RDWR)
51         s.close()
52         
53         if colour == "white":
54                 p = subprocess.Popen(["python", "qchess.py", "@human", "@network:"+addr+":"+port])
55         else:
56                 p = subprocess.Popen(["python", "qchess.py", "@network:"+addr+":"+port, "@human"])
57         p.wait()
58         sys.exit(0)

UCC git Repository :: git.ucc.asn.au