# -*- coding: utf-8 -*- import socket import Tkinter as tk import time SERVER_HOST = '147.185.221.19' SERVER_PORT = 42439 root = tk.Tk() root.title("Simple Chat") root.geometry("400x300") main_frame = tk.Frame(root) main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) main_frame.rowconfigure(0, weight=1) main_frame.rowconfigure(1, weight=0) main_frame.columnconfigure(0, weight=1) text_frame = tk.Frame(main_frame) text_frame.grid(row=0, column=0, sticky="nsew") text_frame.rowconfigure(0, weight=1) text_frame.columnconfigure(0, weight=1) scrollbar = tk.Scrollbar(text_frame) scrollbar.grid(row=0, column=1, sticky="ns") text_area = tk.Text( text_frame, state=tk.DISABLED, yscrollcommand=scrollbar.set, wrap=tk.WORD ) text_area.grid(row=0, column=0, sticky="nsew") scrollbar.config(command=text_area.yview) bottom_frame = tk.Frame(main_frame) bottom_frame.grid(row=1, column=0, sticky="ew", pady=(8, 0)) bottom_frame.columnconfigure(0, weight=1) entry = tk.Entry(bottom_frame) entry.grid(row=0, column=0, sticky="ew") send_button = tk.Button(bottom_frame, text="Send", width=10) send_button.grid(row=0, column=1, padx=(5, 0)) client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.settimeout(0.0) try: client_socket.connect((SERVER_HOST, SERVER_PORT)) except Exception as e: print("Connection failed:", e) def append_message(msg): text_area.config(state=tk.NORMAL) text_area.insert(tk.END, msg + "\n") text_area.config(state=tk.DISABLED) text_area.see(tk.END) def poll_socket(): try: while True: data = client_socket.recv(1024) if not data: break msg = data.strip().replace("*Ping!*", "").strip() if msg: append_message(msg) except: pass root.after(100, poll_socket) def send_message(event=None): msg = entry.get() if msg: try: client_socket.send(msg.encode('utf-8')) entry.delete(0, tk.END) except: append_message("Ошибка отправки.") send_button.config(command=send_message) entry.bind("", send_message) def send_keepalive(): try: client_socket.send("/") except: pass root.after(5000, send_keepalive) def on_close(): try: client_socket.close() except: pass root.destroy() root.protocol("WM_DELETE_WINDOW", on_close) root.after(100, poll_socket) root.after(5000, send_keepalive) root.mainloop()