I am running the following program.
# Server.py
import threading
import socket
host = socket.gethostname()
port = 59000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
aliases = []
def broadcast(message):
for client in clients:
client.send(message)
# Function to handle clients'connections
def handle_client(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
alias = aliases[index]
broadcast(f'{alias} has left the chat room!'.encode('utf-8'))
aliases.remove(alias)
break
# Main function to receive the clients connection
def receive():
while True:
print('Server is running and listening ...')
client, address = server.accept()
print(f'connection is established with {str(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 now connected!'.encode('utf-8'))
thread = threading.Thread(target=handle_client, args=(client,))
thread.start()
if __name__ == "__main__":
receive()
# Client.py
import threading
import socket
alias = input('Choose an alias >>> ')
host = socket.gethostname()
port = 59000
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
def client_receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == "alias?":
client.send(alias.encode('utf-8'))
else:
print(message)
except:
print('Error!')
client.close()
break
def client_send():
while True:
message = f'{alias}: {input("")}'
client.send(message.encode('utf-8'))
receive_thread = threading.Thread(target=client_receive)
receive_thread.start()
send_thread = threading.Thread(target=client_send)
send_thread.start()
Both programs are working fine.
I need to add some logic if a client say bye
then it should be remove.
First I tried to close the client by modifying the client_send():
funtion.
def client_send():
while True:
message = input("")
if message == "bye":
print(f'{alias} has left the chat room!')
client.close()
message = f'{alias}: {message}'
client.send(message.encode('utf-8'))
But this does not work properly. I don’t know how to close the thread as well. It only close the client using client.close()
when bye
is entered by the client but the thread is still running in background.
I get the message.
Exception in thread Thread-2 (client_send):
Traceback (most recent call last):
OSError: [WinError 10038] An operation was attempted on something that is not a socket
I would like to close/stop the thread and also close the client connection . Any idea how to fix/implement ?