parent
f88f316723
commit
c33b07c3a5
@ -1,33 +1,69 @@
|
||||
import tkinter as tk
|
||||
from tkinter import scrolledtext, simpledialog
|
||||
from tkinter import messagebox
|
||||
import socket
|
||||
import threading
|
||||
|
||||
# Configuración del cliente
|
||||
HOST = 'localhost'
|
||||
PORT = 5555
|
||||
class ChatClientGUI:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.root.title("Chat en Grupo")
|
||||
|
||||
# Crear un socket del cliente
|
||||
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
client_socket.connect((HOST, PORT))
|
||||
self.message_list = scrolledtext.ScrolledText(root, height=15, width=50)
|
||||
self.message_list.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
|
||||
|
||||
def receive_messages():
|
||||
"""Recibe mensajes del servidor y muestra en pantalla."""
|
||||
while True:
|
||||
self.entry_message = tk.Entry(root, width=40)
|
||||
self.entry_message.grid(row=1, column=0, padx=10, pady=5)
|
||||
|
||||
self.send_button = tk.Button(root, text="Enviar", command=self.send_message)
|
||||
self.send_button.grid(row=1, column=1, padx=10, pady=5)
|
||||
|
||||
self.username = None
|
||||
self.server_address = "localhost"
|
||||
self.server_port = 5555
|
||||
|
||||
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.setup_connection()
|
||||
|
||||
self.receive_thread = threading.Thread(target=self.receive_messages)
|
||||
self.receive_thread.start()
|
||||
|
||||
def setup_connection(self):
|
||||
try:
|
||||
message = client_socket.recv(1024).decode('utf-8')
|
||||
print(message)
|
||||
except:
|
||||
# En caso de error, salir del bucle
|
||||
break
|
||||
|
||||
def send_messages():
|
||||
"""Envía mensajes al servidor."""
|
||||
while True:
|
||||
message = input()
|
||||
client_socket.send(message.encode('utf-8'))
|
||||
|
||||
# Iniciar hilos para recibir y enviar mensajes
|
||||
receive_thread = threading.Thread(target=receive_messages)
|
||||
receive_thread.start()
|
||||
|
||||
send_thread = threading.Thread(target=send_messages)
|
||||
send_thread.start()
|
||||
self.client_socket.connect((self.server_address, self.server_port))
|
||||
self.username = self.prompt_for_username()
|
||||
self.client_socket.send(self.username.encode('utf-8'))
|
||||
except Exception as e:
|
||||
messagebox.showerror("Error de conexión", f"No se pudo conectar al servidor: {e}")
|
||||
self.root.destroy()
|
||||
|
||||
def prompt_for_username(self):
|
||||
return simpledialog.askstring("Nombre de usuario", "Ingresa tu nombre de usuario:")
|
||||
|
||||
def send_message(self):
|
||||
message = self.entry_message.get()
|
||||
if message:
|
||||
try:
|
||||
self.client_socket.send(message.encode('utf-8'))
|
||||
self.entry_message.delete(0, tk.END)
|
||||
self.message_list.insert(tk.END, f"Yo: {message}\n")
|
||||
self.message_list.yview(tk.END)
|
||||
except:
|
||||
messagebox.showerror("Error", "No se pudo enviar el mensaje. Verifica la conexión.")
|
||||
|
||||
def receive_messages(self):
|
||||
while True:
|
||||
try:
|
||||
message = self.client_socket.recv(1024).decode('utf-8')
|
||||
self.message_list.insert(tk.END, f"Otro: {message}\n")
|
||||
self.message_list.yview(tk.END)
|
||||
self.root.update() # Agregamos esta línea para actualizar la interfaz
|
||||
except:
|
||||
messagebox.showerror("Error", "Se perdió la conexión con el servidor.")
|
||||
self.root.destroy()
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
root = tk.Tk()
|
||||
client_gui = ChatClientGUI(root)
|
||||
root.mainloop()
|
||||
|
Loading…
Reference in new issue