Skip to content
This repository has been archived by the owner on Dec 8, 2021. It is now read-only.

Commit

Permalink
Merge pull request #1 from josxha/master
Browse files Browse the repository at this point in the history
Thx ! python 3 migration
  • Loading branch information
Ganapati authored Oct 1, 2019
2 parents 6e78ffa + 34d005a commit cbb698b
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 77 deletions.
86 changes: 44 additions & 42 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,10 @@ def create_room(self, room_name=None):
"""
Create a new room on server
"""
message = json.dumps({"action": "create",
"payload": room_name,
"identifier": self.identifier})
message = json.dumps({"action": "create", "payload": room_name, "identifier": self.identifier})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
self.sock_tcp.send(message.encode())
data = self.sock_tcp.recv(1024)
self.sock_tcp.close()
message = self.parse_data(data)
Expand All @@ -47,12 +45,10 @@ def join_room(self, room_id):
Join an existing room
"""
self.room_id = room_id
message = json.dumps({"action": "join",
"payload": room_id,
"identifier": self.identifier})
message = json.dumps({"action": "join", "payload": room_id, "identifier": self.identifier})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
self.sock_tcp.send(message.encode())
data = self.sock_tcp.recv(1024)
self.sock_tcp.close()
message = self.parse_data(data)
Expand All @@ -62,8 +58,7 @@ def autojoin(self):
"""
Join the first non-full room
"""
message = json.dumps({"action": "autojoin",
"identifier": self.identifier})
message = json.dumps({"action": "autojoin", "identifier": self.identifier})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
Expand All @@ -76,9 +71,11 @@ def leave_room(self):
"""
Leave the current room
"""
message = json.dumps({"action": "leave",
"room_id": self.room_id,
"identifier": self.identifier})
message = json.dumps({
"action": "leave",
"room_id": self.room_id,
"identifier": self.identifier
})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
Expand All @@ -90,11 +87,10 @@ def get_rooms(self):
"""
Get the list of remote rooms
"""
message = json.dumps({"action": "get_rooms",
"identifier": self.identifier})
message = json.dumps({"action": "get_rooms", "identifier": self.identifier})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
self.sock_tcp.send(message.encode())
data = self.sock_tcp.recv(1024)
self.sock_tcp.close()
message = self.parse_data(data)
Expand All @@ -104,34 +100,42 @@ def send(self, message):
"""
Send data to all players in the same room
"""
message = json.dumps({"action": "send",
"payload": {"message": message},
"room_id": self.room_id,
"identifier": self.identifier})
message = json.dumps({
"action": "send",
"payload": {"message": message},
"room_id": self.room_id,
"identifier": self.identifier
})
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(message, self.server_udp)
sock.sendto(message.encode(), self.server_udp)

def sendto(self, recipients, message):
"""
Send data to one or more player in room
"""
message = json.dumps({"action": "sendto",
"payload": {"recipients": recipients,
"message": message},
"room_id": self.room_id,
"identifier": self.identifier})
message = json.dumps({
"action": "sendto",
"payload": {
"recipients": recipients,
"message": message
},
"room_id": self.room_id,
"identifier": self.identifier
})
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(message, self.server_udp)

def register(self):
"""
Register the client to server and get a uniq identifier
"""
message = json.dumps({"action": "register",
"payload": self.client_udp[1]})
message = json.dumps({
"action": "register",
"payload": self.client_udp[1]
})
self.sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_tcp.connect(self.server_tcp)
self.sock_tcp.send(message)
self.sock_tcp.send(message.encode())
data = self.sock_tcp.recv(1024)
self.sock_tcp.close()
message = self.parse_data(data)
Expand All @@ -148,7 +152,7 @@ def parse_data(self, data):
else:
raise Exception(data['message'])
except ValueError:
print data
print(data)

def get_messages(self):
"""
Expand Down Expand Up @@ -198,37 +202,35 @@ def stop(self):
client2 = Client("127.0.0.1", 1234, 1234, 1236)
client3 = Client("127.0.0.1", 1234, 1234, 1237)

print "Client 1 : %s" % client1.identifier
print "Client 2 : %s" % client2.identifier
print "Client 3 : %s" % client3.identifier
print("Client 1 : %s" % client1.identifier)
print("Client 2 : %s" % client2.identifier)
print("Client 3 : %s" % client3.identifier)

# Create a room on server
client1.create_room("Test room")
print "Client1 create room %s" % client1.room_id
print("Client1 create room %s" % client1.room_id)

# Get rooms list
rooms = client1.get_rooms()
selected_room = None
if rooms is not None and len(rooms) != 0:
for room in rooms:
print "Room %s (%d/%d)" % (room["name"],
int(room["nb_players"]),
int(room["capacity"]))
print("Room %s (%d/%d)" % (room["name"], int(room["nb_players"]), int(room["capacity"])))

# Get first room for tests
selected_room = rooms[0]['id']
else:
print "No rooms"
print("No rooms")

# Join client 1 room
try:
client2.join_room(selected_room)
client3.join_room(selected_room)
except Exception as e:
print "Error : %s" % str(e)
print("Error : %s" % str(e))

print "Client 2 join %s" % client2.room_id
print "Client 3 join %s" % client3.room_id
print("Client 2 join %s" % client2.room_id)
print("Client 3 join %s" % client3.room_id)

# Main game loop
while True:
Expand All @@ -246,4 +248,4 @@ def stop(self):
for message in message:
message = json.loads(message)
sender, value = message.popitem()
print "%s say %s" % (value["name"], value["message"])
print("%s say %s" % (value["name"], value["message"]))
5 changes: 2 additions & 3 deletions player.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ def send_tcp(self, success, data, sock):
success_string = "False"
if success:
success_string = "True"
message = json.dumps({"success": success_string,
"message": data})
sock.send(message)
message = json.dumps({"success": success_string, "message": data})
sock.send(message.encode())

def send_udp(self, player_identifier, message):
"""
Expand Down
61 changes: 29 additions & 32 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,46 +18,46 @@ def main_loop(tcp_port, udp_port, rooms):
udp_server.start()
tcp_server.start()
is_running = True
print "Simple Game Server."
print "--------------------------------------"
print "list : list rooms"
print "room #room_id : print room information"
print "user #user_id : print user information"
print "quit : quit server"
print "--------------------------------------"
print("Simple Game Server.")
print("--------------------------------------")
print("list : list rooms")
print("room #room_id : print room information")
print("user #user_id : print user information")
print("quit : quit server")
print("--------------------------------------")

while is_running:
cmd = raw_input("cmd >")
cmd = input("cmd >")
if cmd == "list":
print "Rooms :"
for room_id, room in rooms.rooms.iteritems():
print "%s - %s (%d/%d)" % (room.identifier,
print("Rooms :")
for room_id, room in rooms.rooms.items():
print("%s - %s (%d/%d)" % (room.identifier,
room.name,
len(room.players),
room.capacity)
room.capacity))
elif cmd.startswith("room "):
try:
id = cmd[5:]
room = rooms.rooms[id]
print "%s - %s (%d/%d)" % (room.identifier,
print("%s - %s (%d/%d)" % (room.identifier,
room.name,
len(room.players),
room.capacity)
print "Players :"
room.capacity))
print("Players :")
for player in room.players:
print player.identifier
print(player.identifier)
except:
print "Error while getting room informations"
print("Error while getting room informations")
elif cmd.startswith("user "):
try:
player = rooms.players[cmd[5:]]
print "%s : %s:%d" % (player.identifier,
print("%s : %s:%d" % (player.identifier,
player.udp_addr[0],
player.udp_addr[1])
player.udp_addr[1]))
except:
print "Error while getting user informations"
print("Error while getting user informations")
elif cmd == "quit":
print "Shutting down server..."
print("Shutting down server...")
udp_server.is_listening = False
tcp_server.is_listening = False
is_running = False
Expand Down Expand Up @@ -89,7 +89,7 @@ def run(self):
self.sock.settimeout(5)
while self.is_listening:
try:
data, addr = self.sock.recvfrom(1024)
data, address = self.sock.recvfrom(1024)
except socket.timeout:
continue

Expand Down Expand Up @@ -140,12 +140,12 @@ def run(self):
finally:
self.lock.release()
except RoomNotFound:
print "Room not found"
print("Room not found")

except KeyError:
print "Json from %s:%s is not valid" % addr
print("Json from %s:%s is not valid" % address)
except ValueError:
print "Message from %s:%s is not valid json string" % addr
print("Message from %s:%s is not valid json string" % address)

self.stop()

Expand Down Expand Up @@ -223,10 +223,10 @@ def run(self):
finally:
self.lock.release()
except KeyError:
print "Json from %s:%s is not valid" % addr
print("Json from %s:%s is not valid" % addr)
conn.send("Json is not valid")
except ValueError:
print "Message from %s:%s is not valid json string" % addr
print("Message from %s:%s is not valid json string" % addr)
conn.send("Message is not a valid json string")

conn.close()
Expand All @@ -250,11 +250,8 @@ def route(self,

if identifier is not None:
if identifier not in self.rooms.players.keys():
print "Unknown identifier %s for %s:%s" % (identifier,
addr[0],
addr[1])
sock.send(self.msg % {"success": "False",
"message": "Unknown identifier"})
print("Unknown identifier %s for %s:%s" % (identifier, addr[0], addr[1]))
sock.send(self.msg % {"success": "False", "message": "Unknown identifier"})
return 0

# Get client object
Expand Down

0 comments on commit cbb698b

Please sign in to comment.