-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.py
71 lines (63 loc) · 2.07 KB
/
Server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Sets up sockets server for multiplayer.
# Citation: 15-112 sockets server framework by Rohan Varma and Kyle Chin
import socket
import threading
from queue import Queue
HOST = "128.237.125.77" # put your IP address here if playing on multiple computers
PORT = 50003
BACKLOG = 2
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(BACKLOG)
print("looking for connection")
def handleClient(client, serverChannel, cID, clientele):
client.setblocking(1)
msg = ""
while True:
try:
msg += client.recv(10).decode("UTF-8")
command = msg.split("\n")
while (len(command) > 1):
readyMsg = command[0]
msg = "\n".join(command[1:])
serverChannel.put(str(cID) + " " + readyMsg)
command = msg.split("\n")
except:
# we failed
return
def serverThread(clientele, serverChannel):
while True:
msg = serverChannel.get(True, None)
print("msg recv: ", msg)
msgList = msg.split(" ")
senderID = msgList[0]
instruction = msgList[1]
details = " ".join(msgList[2:])
if (details != ""):
for cID in clientele:
if cID != senderID:
sendMsg = instruction + " " + senderID + " " + details + "\n"
clientele[cID].send(sendMsg.encode())
print("> sent to %s:" % cID, sendMsg[:-1])
print()
serverChannel.task_done()
clientele = dict()
playerNum = 0
serverChannel = Queue(100)
threading.Thread(target = serverThread, args = (clientele, serverChannel)).start()
# Each possible player
names = ["White", "Black"]
while True:
client, address = server.accept()
myID = names[playerNum]
print(myID, playerNum)
for cID in clientele:
print (repr(cID), repr(playerNum))
clientele[cID].send(("newPlayer %s\n" % myID).encode())
client.send(("newPlayer %s\n" % cID).encode())
clientele[myID] = client
client.send(("myIDis %s \n" % myID).encode())
print("connection recieved from %s" % myID)
threading.Thread(target = handleClient, args =
(client ,serverChannel, myID, clientele)).start()
playerNum += 1