Implementacion de enviar mensajes por servidor chat
This commit is contained in:
parent
7985298e5a
commit
b556eda0cf
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,32 @@
|
|||
import socket
|
||||
import threading
|
||||
|
||||
|
||||
class Chat:
|
||||
def __init__(self, server='127.0.0.1', port=3333):
|
||||
self.server = server
|
||||
self.port = port
|
||||
self.client_socket = None
|
||||
self.connected = False
|
||||
self.mensajes_recibidos = []
|
||||
|
||||
def conectar_al_servidor(self):
|
||||
"""Conectar al servidor de chat."""
|
||||
try:
|
||||
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.client_socket.connect((self.server, self.port))
|
||||
self.connected = True
|
||||
print("Conectado al servidor de chat.")
|
||||
except Exception as e:
|
||||
print(f"Error, no se pudo conectar al servidor: {e}")
|
||||
self.connected = False
|
||||
|
||||
def enviar_mensaje(self, mensaje):
|
||||
"""Enviar un mensaje al servidor."""
|
||||
if not self.connected:
|
||||
raise ConnectionError("No estás conectado al servidor.")
|
||||
try:
|
||||
self.client_socket.send(mensaje.encode('utf-8'))
|
||||
print("Mensaje Enviado")
|
||||
except Exception as e:
|
||||
raise ConnectionError(f"Error al enviar el mensaje: {e}")
|
|
@ -1,11 +1,19 @@
|
|||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
from app.chat import Chat
|
||||
import threading
|
||||
import pygame # Para reproducir música
|
||||
|
||||
|
||||
class PanelDerecho:
|
||||
def __init__(self, frame):
|
||||
# Inicializar el cliente de chat
|
||||
self.chat_client = Chat()
|
||||
try:
|
||||
self.chat_client.conectar_al_servidor()
|
||||
except Exception as e:
|
||||
messagebox.showerror("Error", f"No se pudo conectar al servidor de chat: {e}")
|
||||
|
||||
# Inicializar el reproductor de música
|
||||
pygame.mixer.init()
|
||||
|
||||
|
@ -26,7 +34,7 @@ class PanelDerecho:
|
|||
self.entrada_mensaje.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
|
||||
|
||||
# Botón de enviar
|
||||
boton_enviar = tk.Button(self.frame, text="Enviar", bg="lightgreen", command=self.enviar_mensaje_thread)
|
||||
boton_enviar = tk.Button(self.frame, text="Enviar", bg="lightgreen", command=self.enviar_mensaje)
|
||||
boton_enviar.grid(row=3, column=0, pady=5, padx=5, sticky="ew")
|
||||
|
||||
# Listado de mensajes
|
||||
|
@ -35,13 +43,6 @@ class PanelDerecho:
|
|||
mensajes_frame.columnconfigure(0, weight=1)
|
||||
self.mensajes_frame = mensajes_frame
|
||||
|
||||
# Mensajes iniciales
|
||||
self.mensajes = [
|
||||
{"alumno": "Alumno 1", "texto": "Voy to mal con el trabajo final de DAM, pero seguro que chatgpt me lo hace en nada asiq de chill."},
|
||||
{"alumno": "Alumno 2", "texto": "Me puedes pasar el ultimo trabajo porfa, es que no me a dado tiempo."},
|
||||
]
|
||||
self.actualizar_mensajes()
|
||||
|
||||
# Reproductor de música
|
||||
musica_frame = tk.Frame(self.frame, bg="lightgray", height=50)
|
||||
musica_frame.grid(row=5, column=0, sticky="ew", padx=5, pady=5)
|
||||
|
@ -59,35 +60,21 @@ class PanelDerecho:
|
|||
|
||||
self.frame.rowconfigure(4, weight=1)
|
||||
|
||||
#Metodos para mensajes
|
||||
def enviar_mensaje_thread(self):
|
||||
"""Inicia un hilo para agregar un mensaje."""
|
||||
threading.Thread(target=self.enviar_mensaje, daemon=True).start()
|
||||
|
||||
# Métodos del chat
|
||||
def enviar_mensaje(self):
|
||||
"""Agrega un mensaje al listado."""
|
||||
"""Enviar un mensaje al servidor."""
|
||||
texto = self.entrada_mensaje.get("1.0", tk.END).strip()
|
||||
if texto:
|
||||
self.mensajes.append({"alumno": "Tú", "texto": texto})
|
||||
self.entrada_mensaje.delete("1.0", tk.END)
|
||||
self.actualizar_mensajes()
|
||||
try:
|
||||
self.chat_client.enviar_mensaje(texto)
|
||||
self.entrada_mensaje.delete("1.0", tk.END)
|
||||
except Exception as e:
|
||||
messagebox.showerror("Error", f"No se pudo enviar el mensaje: {e}")
|
||||
else:
|
||||
messagebox.showwarning("Aviso", "El mensaje está vacío.")
|
||||
|
||||
def actualizar_mensajes(self):
|
||||
"""Actualiza el listado de mensajes en la interfaz."""
|
||||
for widget in self.mensajes_frame.winfo_children():
|
||||
widget.destroy()
|
||||
|
||||
for mensaje in self.mensajes:
|
||||
tk.Label(self.mensajes_frame, text=mensaje["alumno"], font=("Helvetica", 10, "bold"), anchor="w").pack(
|
||||
fill="x", padx=5, pady=2
|
||||
)
|
||||
tk.Label(
|
||||
self.mensajes_frame, text=mensaje["texto"], font=("Helvetica", 9), anchor="w", wraplength=180, justify="left"
|
||||
).pack(fill="x", padx=5, pady=2)
|
||||
|
||||
# Metodos para control de música
|
||||
# Métodos para control de música
|
||||
def reproducir_musica_thread(self):
|
||||
"""Inicia un hilo para reproducir música."""
|
||||
threading.Thread(target=self.reproducir_musica, daemon=True).start()
|
||||
|
|
Loading…
Reference in New Issue