From b610ddcaa1ea50db49664e481a39622f0c07a44a Mon Sep 17 00:00:00 2001 From: AvishkaWeebadde Date: Thu, 22 Oct 2020 11:17:10 +0530 Subject: [PATCH] A simple TCP chatting client with python --- TCP_chatroom/client.py | 39 ++++++++++++++++++++++++++++ TCP_chatroom/server.py | 58 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 TCP_chatroom/client.py create mode 100644 TCP_chatroom/server.py diff --git a/TCP_chatroom/client.py b/TCP_chatroom/client.py new file mode 100644 index 0000000..1cc177a --- /dev/null +++ b/TCP_chatroom/client.py @@ -0,0 +1,39 @@ +import socket +import threading + +alias = input("choose a alias/nickanme: ") + +client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +client.connect(('127.0.0.1', 55556)) + +# sending alias to the server +def receive(): + while True: + try: + message = client.recv(1024).decode('ascii') + if message == 'NICK': + client.send(alias.encode('ascii')) + else: + print(message) + + except: + print("An error occured!") + client.close() + break + +# sending messages +def write(): + while True: + message ='{}: {}'.format(alias, input('')) + client.send(message.encode('ascii')) + + +receive_thread = threading.Thread(target=receive) +receive_thread.start() + +write_thread = threading.Thread(target=write) +write_thread.start() + + + + diff --git a/TCP_chatroom/server.py b/TCP_chatroom/server.py new file mode 100644 index 0000000..d921b51 --- /dev/null +++ b/TCP_chatroom/server.py @@ -0,0 +1,58 @@ +import threading +import socket + + +host = '127.0.0.1' +port = 55556 + +# Starting Server +server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +server.bind((host, port)) +server.listen() + +clients = [] +aliases = [] + +def broadcast(message): # send the message to whole network + for client in clients: + client.send(message) + + +def handle(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} left the chat'.encode('ascii')) + aliases.remove(alias) + break + +def receive(): + while True: + client, address = server.accept() # confirm connection + print(f'connected with {str(address)}') + + client.send('NICK'.encode('ascii')) # nickname storage + alias = client.recv(1024).decode('ascii') + aliases.append(alias) + clients.append(client) + + print(f'Nickname of the client is {alias}') + broadcast(f'{alias} joined the chat!'.encode('ascii')) + client.send('Connected to the server!'.encode('ascii')) + + + thread = threading.Thread(target=handle, args=(client,)) + thread.start() + + + +print("server is listening") +receive() + +