mail@pastecode.io avatarunknown
12 days ago
3.4 kB
import socket
import tkinter as tk
import threading
from tkinter import messagebox

HOST = ''
PORT = 65432

class ChatServerGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("Chat Application")

        # Entry to set an alias for the user
        self.alias_label = tk.Label(self.master, text="Your Alias:")
        self.alias_label.pack(pady=5, padx=10)
        self.alias_entry = tk.Entry(self.master)
        self.alias_entry.pack(pady=5, padx=20, fill=tk.X)

        self.messages_frame = tk.Frame(self.master)
        self.scrollbar = tk.Scrollbar(self.messages_frame)
        # Listbox to display incoming and outgoing messages
        self.msg_list = tk.Listbox(self.messages_frame, height=20, width=50, yscrollcommand=self.scrollbar.set)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH)
        self.msg_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.messages_frame.pack(pady=10, padx=10)

        # Input fields for the target IP and the message content
        self.target_ip_label = tk.Label(self.master, text="Send to IP:")
        self.target_ip_label.pack(pady=5, padx=10)
        self.target_ip_entry = tk.Entry(self.master)
        self.target_ip_entry.pack(pady=5, padx=20, fill=tk.X)

        self.message_label = tk.Label(self.master, text="Message:")
        self.message_label.pack(pady=5, padx=10)
        self.message_entry = tk.Entry(self.master)
        self.message_entry.pack(pady=5, padx=20, fill=tk.X)

        # Send button to transmit the message
        self.send_button = tk.Button(self.master, text="Send", command=self.send_message)

        # Start the server thread
        self.start_server_thread = threading.Thread(target=self.start_server)

    def start_server(self):
        """Starts the UDP server to listen for incoming messages."""
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.bind((HOST, PORT))
            while True:
                data, addr = s.recvfrom(1024)
                # The format of incoming data will be 'alias:message'
                alias, message = data.decode().split(':', 1)
                display_message = f"{alias}: {message}"
                self.msg_list.insert(tk.END, display_message)

    def send_message(self):
        """Sends the message to the specified IP."""
        target_ip = self.target_ip_entry.get().strip()
        message = self.message_entry.get().strip()
        alias = self.alias_entry.get().strip()

        # Ensure the necessary fields are filled
        if not target_ip or not message or not alias:
            messagebox.showerror("Error", "IP, alias, and message fields should be filled!")

        # Append the alias to the message before sending
        full_message = f"{alias}:{message}"

            with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
                s.sendto(full_message.encode(), (target_ip, PORT))
            display_message = f"You ({alias}) to {target_ip}: {message}"
            self.msg_list.insert(tk.END, display_message)
        except Exception as e:
            messagebox.showerror("Error", f"Failed to send the message: {e}")

if __name__ == "__main__":
    root = tk.Tk()
    gui = ChatServerGUI(root)