Archived
1
0
Fork 0

Add RLock on clients dictionary for safe shared resources

This commit is contained in:
Ethanell 2019-07-21 20:18:39 +02:00
parent da0e1549a2
commit 6e47a44184

View file

@ -1,4 +1,4 @@
from threading import Thread
from threading import Thread, RLock
from SecureSocketService import Socket
from socket import error as socket_error
@ -14,6 +14,7 @@ class Server(Socket):
self.welcome_msg = "Welcome ! Type \"/help\" to see commands and \"quit\" to exit"
self.commands = {"help": self.command_help, "players list": self.command_players_list}
self.clients = dict()
self.clients_lock = RLock()
print("Wait for connexion...")
Thread(target=self.connexion).start()
@ -26,8 +27,9 @@ class Server(Socket):
else:
name = self.client_name(c)
if name:
with self.clients_lock:
self.clients[name] = c
self.send(self.clients[name], self.welcome_msg)
self.send(c, self.welcome_msg)
self.broadcast(f"{name} is online !")
Thread(target=self.listen_client, args=(name,)).start()
@ -36,6 +38,7 @@ class Server(Socket):
try:
self.send(sock, "Your name ?")
name = self.receive(sock)
with self.clients_lock:
if name in self.clients:
self.send(sock, "Name already taken !")
elif name.lower() == "quit":
@ -62,6 +65,7 @@ class Server(Socket):
def broadcast(self, message):
print(message)
with self.clients_lock:
for i in self.clients:
try:
self.send(self.clients[i], message)
@ -69,6 +73,7 @@ class Server(Socket):
continue
def client_quit(self, name):
with self.clients_lock:
try:
self.send(self.clients[name], "quit")
self.clients[name].close()
@ -99,9 +104,11 @@ class Server(Socket):
message = "[Help]"
for i in self.commands:
message += "\n- " + i
with self.clients_lock:
self.send(self.clients[author], message)
def command_players_list(self, author):
with self.clients_lock:
message = f"[Players list | {len(self.clients)} online]"
for i in self.clients:
message += "\n- " + i