You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.6 KiB
70 lines
2.6 KiB
import tkinter as tk
|
|
from tkinter import scrolledtext, simpledialog
|
|
from tkinter import messagebox
|
|
import socket
|
|
import threading
|
|
|
|
class ChatClientGUI:
|
|
def __init__(self, root):
|
|
self.root = root
|
|
self.root.title("Chat en Grupo")
|
|
|
|
self.message_list = scrolledtext.ScrolledText(root, height=15, width=50)
|
|
self.message_list.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
|
|
|
|
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:
|
|
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()
|