Skip to content

Instantly share code, notes, and snippets.

@ajangrahmat
Last active October 2, 2024 10:41
Show Gist options
  • Save ajangrahmat/71987ab8816a749451fb4851d8954695 to your computer and use it in GitHub Desktop.
Save ajangrahmat/71987ab8816a749451fb4851d8954695 to your computer and use it in GitHub Desktop.
Coding Chat MQTT
import random
import threading
from paho.mqtt import client as mqtt_client
broker = 'broker.emqx.io'
port = 1883
topic = "chat/82812181"
client_id = input("Enter your name: ")
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print(f"{client_id} connected to MQTT Broker!")
else:
print(f"Failed to connect, return code {rc}\n")
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
message = msg.payload.decode()
print(f"{message}")
client.subscribe(topic)
client.on_message = on_message
def publish(client: mqtt_client):
while True:
msg = input()
formatted_msg = f"{client_id}: {msg}"
client.publish(topic, formatted_msg)
def run():
client = connect_mqtt()
subscribe(client)
client.loop_start()
publish(client)
client.loop_stop()
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment