0% found this document useful (0 votes)
6 views3 pages

Client Gui

The document contains Python code for a chat client that utilizes sockets and a graphical user interface with Tkinter. It allows users to connect to a server, send and receive messages, and displays the chat in a scrollable text area. The client prompts for a username and handles message sending and receiving in separate threads.

Uploaded by

Tanish Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Client Gui

The document contains Python code for a chat client that utilizes sockets and a graphical user interface with Tkinter. It allows users to connect to a server, send and receive messages, and displays the chat in a scrollable text area. The client prompts for a username and handles message sending and receiving in separate threads.

Uploaded by

Tanish Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

"""

import socket
import threading

def receive_messages(sock):
while True:
try:
data = sock.recv(1024).decode()
if not data:
break
print(data)
except:
break

def start_client(host='172.17.4.193', port=8080):


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))

threading.Thread(target=receive_messages, args=(s,), daemon=True).start()

name = input()
s.sendall(name.encode())

while True:
#s.recv(1024).decode()
msg = input("<Me>: ")
if msg.lower() == 'exit':
s.sendall(msg.encode())
break
s.sendall(msg.encode())

if __name__ == '__main__':
start_client()
"""

import socket
import threading
import tkinter as tk
from tkinter import simpledialog, scrolledtext, messagebox

class ChatClient:
def __init__(self, host='192.168.1.4', port=65432):
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = port

self.root = tk.Tk()
self.root.title("Python Chat Client")
self.root.protocol("WM_DELETE_WINDOW", self.on_close)

self.chat_display = scrolledtext.ScrolledText(self.root, state='disabled',


width=50, height=20)
self.chat_display.pack(padx=10, pady=10)

self.entry = tk.Entry(self.root, width=40)


self.entry.pack(side=tk.LEFT, padx=(10, 0), pady=(0, 10))
self.entry.bind("<Return>", self.send_message)

self.send_button = tk.Button(self.root, text="Send",


command=self.send_message)
self.send_button.pack(side=tk.LEFT, padx=(5, 10), pady=(0, 10))

self.name = simpledialog.askstring("Name", "Enter your name:",


parent=self.root)
if not self.name:
messagebox.showerror("Error", "Name is required!")
self.root.destroy()
return

self.connect()
threading.Thread(target=self.receive_messages, daemon=True).start()
self.root.mainloop()

def connect(self):
try:
self.client_socket.connect((self.host, self.port))
self.client_socket.recv(1024) # "Enter your name:" prompt
self.client_socket.sendall(self.name.encode())
except Exception as e:
messagebox.showerror("Connection Error", str(e))
self.root.destroy()

def send_message(self, event=None):


message = self.entry.get()
if message:
try:
self.client_socket.sendall(message.encode())
self.entry.delete(0, tk.END)
if message.lower() == 'exit':
self.root.quit()
except:
messagebox.showerror("Error", "Failed to send message.")

def receive_messages(self):
while True:
try:
data = self.client_socket.recv(1024).decode()

split_list = data.split(":", 1)
if self.name in split_list[0]:
split_list[0] = split_list[0].replace(self.name, "Me:")
new_data = split_list[0] + split_list[1]
else:
new_data = data
if not data:
break
self.chat_display.config(state='normal')
self.chat_display.insert(tk.END, new_data + "\n")
self.chat_display.yview(tk.END)
self.chat_display.config(state='disabled')
except:
break

def on_close(self):
try:
self.client_socket.sendall("exit".encode())
except:
pass
self.client_socket.close()
self.root.quit()

if __name__ == '__main__':
ChatClient()

You might also like