added multithreading

This commit is contained in:
Daniel Jones 2024-09-11 14:39:38 -05:00
parent 17c5c8557d
commit 1d17fec7ca
2 changed files with 63 additions and 21 deletions

View File

@ -1,14 +1,30 @@
import threading
import socket
alias = input("choose an alias: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 9999))
client.connect(('127.0.0.1', 9999))
done = False
while not done:
client.send(input("message: ").encode('utf-8'))
msg = client.recv(1024).decode('utf-8')
if msg != "quit":
print(msg)
def client_receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == "alias?":
client.send(alias.encode('utf-8'))
else:
done = True
print(message)
except:
print('error')
client.close()
break
def client_send():
while True:
message = f'{alias}: {input("")}'
client.send(message.encode('utf-8'))
recieve_thread = threading.Thread(target = client_receive)
recieve_thread.start()
send_thread = threading.Thread(target=client_send)
send_thread.start()

View File

@ -1,19 +1,45 @@
import threading
import socket
host = "127.0.0.1"
port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 9999))
server.bind((host, port))
server.listen()
clients = []
aliases = []
client, addr = server.accept()
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
done = False
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()
while not done:
msg = client.recv(1024).decode('utf-8')
if msg == 'quit':
done = True
else:
print(msg)
client.send(input("Message: ").encode('utf-8'))