Question: May you help me implement the following in my code: - Allow Client to leave the system by implementing a command. Use the username passed

May you help me implement the following in my code:
- Allow Client to leave the system by implementing a command. Use the username
passed to client.py to print [username] has left on all other connected Clients.
- Allow Client to leave the system unexpectedly. Use the username passed to client.py
to print [username] has left on all other connected Clients
- One of the connected clients disconnecting should not cause the server to crash
- Client should be able to unicast messages to another client individually when there
are more than two clients in the system. They also should be able to change between broadcast and unicast
- In case of a crash, attempt to close remaining connections and print an error messagein the terminals of all previous connected devices.
my code :
server.py:
import socket
import threading
import sys
def main(port):
host = 'localhost'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients =[]
usernames=[]
def broadcast(message, sender_client=None):
for client in clients:
if client != sender_client:
client.send(message)
def handle_client(client):
while True:
try:
message =client.recv(1024)
broadcast(message,client)
except:
index = clients.index(client)
clients.remove(client)
client.close()
username = usernames[index]
broadcast(f'{username} has left'.encode())
usernames.remove(username)
break
def receive_client():
while True:
client, address = server.accept()
print(f"Connection coming from {str(address)}")
client.send('Username'.encode())
username = client.recv(1024).decode()
usernames.append(username)
clients.append(client)
print(f'{username} has joined')
broadcast(f"{username} has joined".encode())
client.send('Welcome to the server'.encode())
thread = threading.Thread(target= handle_client , args=(client,))
thread.start()
receive_client()
if __name__=="__main__":
if len(sys.argv)<1:
print("Usage: python3 server.py [port]")
else:
main(int(sys.argv[1]))
client.py:
import socket
import threading
import sys
def main(username, hostname, port):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((hostname, port))
except Exception as e:
print(f"Could not connect: {e}")
def receive_mesage():
while True:
try:
message = client.recv(1024).decode()
if message == 'Username':
client.send(username.encode())
else:
print(message)
except Exception as e:
print(f"Error: {e}")
client.close()
break
def write():
while True:
message = f'{username}: {input("")}'
if message == "command":
command = input(f'{username}command >')
if command =="/exit":
client.send("/exit".encode())
break
elif command.startswith("/broadcast"):
client.send(command.encode())
elif command.startswith("/unicast"):
client.send(command.encode())
elif command =="/files":
client.send("/files".encode())
elif command.startswith("/download"):
client.send(command.encode())
else:
print("Invalid command.")
client.close()
else:
client.send(message.encode())
receive_thread = threading.Thread(target= receive_mesage)
receive_thread.start()
write_thread = threading.Thread(target= write)
write_thread.start()
if __name__=="__main__":
if len(sys.argv)<4:
print("Usage: python client.py [username][hostname][port]")
else:
main(sys.argv[1], sys.argv[2], int(sys.argv[3]))

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!