본문 바로가기
  • 👩🏻‍💻 🌮 💬
🍔 database

[MQTT] python 으로 sub / pub 구현하기

by 바쿄리 2024. 10. 28.
 

MQTT와 Kakfa 비교

개요최근에 진행한 프로젝트 중에 socket 통신으로 데이터를 보내고, responce를 받는 기능을 개발했는데네트워크가 불안정한 환경에서 진행하니까 socket 연결 불안정, 연결 지연 등등 이슈들이 발

bonory.tistory.com

kafka와 mqtt에 대해서 찾아보고 정리했다.

그리고는 mqtt를 한번 사용해 보려고 한다.

 

진행

1. python으로 topic에 message를 전송한다.

2. MQTT Explorer로 message를 잘 받는지 확인한다.

3. python으로 topic을 subscribe하고 message를 확인한다.

 

(0) pip 설치

pip install paho-mqtt

 

(1) python - message 전송

import paho.mqtt.client as mqtt

BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "topicA"

client = mqtt.Client()

client.connect(BROKER, PORT, 60)

def publish_message(client, topic, message):
    client.publish(topic, message)
    print(f"Sent message: {message} on topic: {topic}")
    
client.loop_start()

try:
    publish_message(client, TOPIC, "Hello, this is a test message")
finally:
    client.loop_stop()
    client.disconnect()

 

> 실행하면 아래와 같이 확인할 수 있다.

Sent message: Hello, this is a test message on topic: topicA

 

(2) MQTT Explorer

아래와 같이 message를 확인할 수 있다.

 

(3) python - message 받기

import paho.mqtt.client as mqtt

BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "topicA"

def on_message(client, userdata, message):
    print(f"Received message: '{message.payload.decode()}' on topic: '{message.topic}'")

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker successfully")
        client.subscribe(TOPIC)
        print(f"Subscribed to topic: {TOPIC}")
    else:
        print(f"Failed to connect, return code {rc}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(BROKER, PORT, 60)

client.loop_forever()

 

> 실행하면 client에 연결된 상태를 유지하며, (1) message 전송 에서 보내는 message를 받을 수 있다.

Connected to broker successfully
Subscribed to topic: topicA
Received message: 'Hello, this is a test message' on topic: 'topicA'

 

'🍔 database' 카테고리의 다른 글

크롤링 데이터 적재 SQL vs NoSQL  (0) 2025.02.06
[MongoDB] 간단한 개념정리  (0) 2025.01.10
MQTT와 Kakfa 비교  (2) 2024.10.23
mysql 데이터 변경 실시간 확인 진행  (3) 2024.10.20
mysql 데이터 변경 실시간 확인  (2) 2024.10.02