QND_secure_chat/server.py

46 lines
1.1 KiB
Python
Raw Permalink Normal View History

2024-09-11 19:39:38 +00:00
import threading
2024-09-11 18:17:11 +00:00
import socket
2024-09-11 19:39:38 +00:00
host = "127.0.0.1"
port = 9999
2024-09-11 18:17:11 +00:00
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2024-09-11 19:39:38 +00:00
server.bind((host, port))
2024-09-11 18:17:11 +00:00
server.listen()
2024-09-11 19:39:38 +00:00
clients = []
aliases = []
2024-09-11 18:17:11 +00:00
2024-09-11 19:39:38 +00:00
def broadcast(message):
for client in clients:
client.send(message)
def handle_client(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
client.close()
alias = aliases[index]
broadcast(f'{alias} has left the chat room!'.encode('utf-8'))
aliases.remove(alias)
break
2024-09-11 18:17:11 +00:00
2024-09-11 19:39:38 +00:00
def receive():
while True:
print("server is running and listening")
client, address = server.accept()
print(f'connection is established with {(address)}')
client.send('alias?'.encode('utf-8'))
alias = client.recv(1024)
aliases.append(alias)
clients.append(client)
print(f'The alias of this client is {alias}'.encode('utf-8'))
broadcast(f'{alias} has connected to the chat room'.encode('utf-8'))
client.send("you are connected!".encode('utf-8'))
thread = threading.Thread(target = handle_client, args=(client,))
thread.start()
if __name__ == "__main__":
receive()
2024-09-11 18:17:11 +00:00