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

Real-Time Desktop Chat App

Uploaded by

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

Real-Time Desktop Chat App

Uploaded by

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

We are to build an application that allows users on a LAN to chat with each other in real-time.

This application will use the classes for socket communication we created earlier.

Here's how it will work:

Connect multiple computers on the same LAN


Each desktop app instance on the computers will be identified with a username and id (we
are going to hard code these or allow the users to input their desired names and ids)
Each desktop app will have a socket client. One person on the network will start the
server, the other clients will connect to it
When a message is sent from one instance, all the other apps connected on the network
should receive it.

Create a new file chat_gui.py in the same folder as the socket_server.py and
socket_client.py . This app uses the customtkinter package so be sure to install it before you
get started.

Put the following code in the chat_gui.py file

import customtkinter as ctk

from socket_client import Client as SocketClient

ctk.set_appearance_mode("light")
ctk.set_default_color_theme("dark-blue")

class ChatApp(ctk.CTk):
def __init__(self, messages=None, user={"username": "Prince", "id": 1},
width=300, server_host=None, server_port=None):
super().__init__()

self.username = user['username']
self.id = user['id']

self.title(f"Python Chat - {self.username}")

# frame to contain the messages sent and received


self.messages_frame = ctk.CTkScrollableFrame(master=self, width=self.width)
self.messages_frame.grid(row=0, column=0)

self.width = width
# input box for a message
self.entry = ctk.CTkEntry(master=self, width=300)
self.entry.grid(row=1, column=0, pady=10)
self.entry.focus()

self.messages = messages if messages else []

self.create_widgets()

# process key press events with the key_pressed method


self.bind('<Key>', self.key_pressed)

# create a socket client if a server_host and server_port are


specified
self.socket_client = None
if server_host and server_port:
# run the method to add a message when the socket client receives a
message from the server
on_message_receive = lambda message: self.add_message(message)
self.socket_client = SocketClient(server_host, server_port,
on_message_receive=on_message_receive, username=self.username, user_id=self.id)

def create_widgets(self):
for index, message in enumerate(self.messages):
self.display_message(message, index)

def display_message(self, message, index):


"""
Method to add a message to the scrollable frame.
It puts the message on the left of the screen if it is not sent by the
app user
Else it puts the message on the right
"""
# check if the message was sent by the user of the app
is_message_sent_by_user = message["user"]["id"] == self.id

# put frame on the left if the message was not sent by the user
frame = ctk.CTkFrame(master=self.messages_frame, width=self.width/2)
frame.grid(row=index, column=0 if not is_message_sent_by_user else 1,
padx=10, pady=10)

text_box = ctk.CTkTextbox(frame, width=(self.width / 2) - 10, height=80,


wrap="word")
text_box.grid(row=0, column=0)
text_box.insert("0.0", f"""{"You" if is_message_sent_by_user else
message["user"]["name"]}\n{message["message"]}""")
text_box.configure(state="disabled")

def add_message(self, message):


self.display_message(message, index=len(self.messages))
self.messages.append(message)

def key_pressed(self, event):


# if the message entry box is focused
if self.entry._is_focused:
key = event.char
if key == '\r':
message= {
"user": {
"id": self.id,
"name": self.username
},
"message": self.entry.get()
}
self.add_message(message)
self.socket_client.send_message(message)
print(f"Sending message {message}")

if __name__ == '__main__':
username = input("What's your username? ")
userid = input("Provide your id: ")

app = ChatApp(
user={"username": username, "id": userid},
server_host="localhost", server_port=12345
)
app.mainloop()

Run the app, try sending a message to your network neighbours.

You might also like