Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import tkinter as tk
import paho.mqtt.client as mqtt
#Justice
#Asoro
# Callback when the client connects to the broker
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# Subscribe to the private chat topics
client.subscribe("private_chat/user1")
client.subscribe("private_chat/user2")
# Callback when a message is received
def on_message(client, userdata, msg):
received_message = msg.payload.decode()
print(f"Received message on topic {msg.topic}: {received_message}")
# Display received message in the UI
if msg.topic == "private_chat/user1":
chat_display.insert(tk.END, "User1: " + received_message + "\n")
elif msg.topic == "private_chat/user2":
chat_display.insert(tk.END, "User2: " + received_message + "\n")
chat_display.see(tk.END)
# Function to send a message
def send_message(event=None):
user_input = message_entry.get()
if user_input.lower() == "exit":
client.loop_stop()
client.disconnect()
root.destroy()
else:
client.publish("private_chat/user1", user_input)
client.publish("private_chat/user2", user_input)
message_entry.delete(0, tk.END)
# Create a client instance
client = mqtt.Client()
# Set the callbacks
client.on_connect = on_connect
client.on_message = on_message
# Connect to the broker
client.connect("broker.hivemq.com", 1883)
# Start the MQTT loop (this handles communication)
client.loop_start()
# Create the UI
root = tk.Tk()
root.title("MQTT Chat")
chat_display = tk.Text(root)
chat_display.pack(expand=True, fill=tk.BOTH)
message_entry = tk.Entry(root)
message_entry.pack(side=tk.BOTTOM, fill=tk.X)
message_entry.focus()
send_button = tk.Button(root, text="Send", command=send_message)
send_button.pack(side=tk.BOTTOM)
# Bind Enter key to send_message function
root.bind("<Return>", send_message)
# Start the UI loop
root.mainloop()
print("Chat ended. Goodbye!")