Add chat project

This commit is contained in:
Manuel Vergara 2024-01-25 22:26:39 +01:00
parent bd197dc519
commit c0b6b881e4
4 changed files with 213 additions and 0 deletions

View File

@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""
CLIENTE DE CHAT CIFRADO E2E
"""
import socket as s
import threading as th
from tkinter import *
from tkinter.scrolledtext import ScrolledText
def send_message(client_socket, username, text_widget, entry_widget):
local_address = client_socket.getsockname()
ip_address, port = local_address
message = entry_widget.get()
client_socket.sendall(
f'{username} ({ip_address}:{port}): {message}\n'.encode())
entry_widget.delete(0, END)
text_widget.configure(state='normal')
text_widget.insert(END, f'{username} ({ip_address}:{port}): {message}\n')
text_widget.configure(state='disabled')
def receive_message(client_socket, text_widget):
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
text_widget.configure(state='normal')
text_widget.insert(END, message)
text_widget.configure(state='disabled')
except:
break
def list_users_request(client_socket):
client_socket.sendall("!usuarios".encode())
def exit_request(client_socket, username, window):
client_socket.sendall(
f"\n[!] El usuario {username} ha abandonado el chat\n".encode()
)
client_socket.close()
window.quit()
window.destroy()
def client_program():
host = 'localhost'
port = 1234
client_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
client_socket.connect((host, port))
username = input("\n[+] Introduce tu usuario: ")
if not username:
username = "Anonymus"
client_socket.sendall(username.encode())
window = Tk()
window.title(f'Chat cifrado E2E - {username}')
# window.geometry('500x700')
# window.iconbitmap("oveja-negra.ico")
# window.iconphoto(False, PhotoImage(file="oveja-negra.png"))
text_widget = ScrolledText(window, state='disabled')
text_widget.pack(padx=5, pady=5)
frame_widget = Frame(window)
frame_widget.pack(fill=BOTH, expand=True, padx=5, pady=5)
entry_widget = Entry(frame_widget, font=('Arial', 12))
entry_widget.bind(
"<Return>",
lambda _: send_message(
client_socket, username,
text_widget, entry_widget
)
)
entry_widget.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)
button_widget = Button(
frame_widget, text="Enviar",
command=lambda: send_message(
client_socket, username,
text_widget, entry_widget
)
)
button_widget.pack(side=RIGHT, padx=5, pady=5)
users_widget = Button(
window, text="Listar usuarios",
command=lambda: list_users_request(client_socket))
users_widget.pack(padx=5, pady=5)
exit_widget = Button(
window, text="Salir",
command=lambda: exit_request(client_socket, username, window))
exit_widget.pack(padx=5, pady=5)
thread = th.Thread(
target=receive_message,
args=(client_socket, text_widget)
)
thread.daemon = True
thread.start()
window.mainloop()
client_socket.close()
if __name__ == '__main__':
client_program()

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""
SERVER DE CHAT CIFRADO E2E
"""
import socket as s
import threading as th
def client_thread(client_socket, clients, usernames):
username = client_socket.recv(1024).decode()
usernames[client_socket] = username
print(f"\n[+] El usuario {username} se ha conectado al chat")
for client in clients:
if client is not client_socket:
client.sendall(
f"\n[+] El usuario {username} se ha conectado al chat\n\n".encode()
)
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
if message == "!usuarios":
client_socket.sendall(
f"\n[i] Usuarios conectados: {', '.join(usernames.values())}\n\n".encode()
)
continue
for client in clients:
if client is not client_socket:
client.sendall(message.encode())
except:
break
client_socket.close()
clients.remove(client_socket)
del usernames[client_socket]
def server_program():
host = 'localhost'
port = 1234
server_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
server_socket.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1) # TIME_WAIT
server_socket.bind((host, port))
server_socket.listen()
print(f"\n[+] Server está en escucha...")
clients = []
usernames = {}
while True:
client_socket, addr = server_socket.accept()
clients.append(client_socket)
print(f"\n[+] Conectado a {addr}")
thread = th.Thread(
target=client_thread,
args=(client_socket, clients, usernames)
)
thread.daemon = True
thread.start()
server_socket.close()
if __name__ == '__main__':
server_program()