[C#] MQTT 통신 클라이언트 예제

💫 MQTT란?


MQTT(메시지 큐잉 텔레메트리 트랜스포트, Message Queuing Telemetry Transport)는 ISO 표준(ISO/IEC PRF 20922) 발행-구독 기반의 메시징 프로토콜이다.
TCP/IP 프로토콜 위에서 동작한다. "작은 코드 공간"(small code footprint)이 필요하거나 네트워크 대역폭이 제한되는 원격 위치와의 연결을 위해 설계되어 있다. 발행-구독 메시징 패턴은 메시지 브로커가 필요하다.

 

💫 예제 설명

클라이언트 프로그램 두개를 생성해서 각자 클라이언트에서 보내는 메세지를 상대 클라이언트에 뜨도록 하는 프로젝트이다 .
 

💫 실행 전 다운받아야하는 것들

1. 브로커는 Mosquitto를 다운받아 사용
2. NuGet 패키지 M2Mqtt 설치


 

💫 Mosquitto 시작

1. cmd창에서 Mosquitto가 설치된 경로로 이동

cd C:\Program Files\mosquitto

2. 이동한뒤 Mosquitto broker 실행(-v : 모든 통신과정을 보여주는 옵션)

mosquitto -v

 

💫 클라이언트 form 형태


 

💫 클라이언트 시작

1. Start 버튼을 누르면 클라이언트-broker 연결 시작


 

💫 전송 및 종료

1. 메세지 전송

전송버튼을 누르면 수신 클라이언트의 수신메세지 label에 메세지표시

2. 클라이언트가 종료되었을때


 

💫 클라이언트 소스 코드

클라이언트 소스 코드는 수신/발신 토픽만 다름!!

1. Client 1
using System;
using System.Net;
using System.Reflection.Emit;
using System.Text;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace Client
{
    public partial class Form1 : Form
    {
        private MqttClient client;

        public Form1()
        {
            InitializeComponent();
            //폼 닫기 이벤트 선언
            this.FormClosed += Form1_FormClosing;
        }
        /// <summary>
        /// 폼 닫기 이벤트 핸들러 선언
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosedEventArgs e)
        {
            if (client != null && client.IsConnected)
            {
                client.Disconnect();
            }
        }
        /// <summary>
        /// 수신 메세지 표시
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // 수신된 메시지를 변수에 저장
            string receivedMessage = Encoding.UTF8.GetString(e.Message);

            // UI 업데이트를 위해 UI 스레드로 전달
            Invoke(new Action(() =>
            {
                // receivedMessage를 Form label ReceivedText에 표시
                ReceivedText.Text = receivedMessage;
            }));
        }
        /// <summary>
        /// start 버튼 클릭했을때 실행
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Startbutton_Click(object sender, EventArgs e)
        {
            // MQTT 브로커 주소
            string MQTT_BROKER_ADDRESS = "127.0.0.1";

            // 클라이언트 인스턴스 생성
            client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

            // 메시지 수신 시 이벤트 핸들러 등록
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            // 고유한 클라이언트 ID 생성
            string clientId = "COOKIE";

            try
            {
                client.Connect(clientId);
                //연결이 성공하면 Serverconnect에 성공 메세지출력
                if (client.IsConnected) Serverconnect.Text = "SERVER " + MQTT_BROKER_ADDRESS + "와 연결 성공!";
            }
            catch (Exception ex)
            {
                //연결이 실패하면 Serverconnect에 실패 메세지, 오류메세지 출력
                Serverconnect.Text = "브로커에 연결할 수 없습니다.\n" + ex.Message + "연결 오류";
            }

            // 수신 토픽 "coorong" 구독
            client.Subscribe(new string[] { "coorong" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
        /// <summary>
        /// Send버튼 클릭했을때 실행
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sendbutton_Click(object sender, EventArgs e)
        {
            // 보낼 메시지
            string messageToSend = SendText.Text;

            // 발신 토픽 "cookie", 메세지 발송
            client.Publish("cookie", Encoding.UTF8.GetBytes(messageToSend), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);

            //메세지박스 초기화
            SendText.Text = "";
        }
    }
}

 

2. Client 2
using System;
using System.Net;
using System.Reflection.Emit;
using System.Text;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace Client
{
    public partial class Form1 : Form
    {
        private MqttClient client;

        public Form1()
        {
            InitializeComponent();
            //폼 닫기 이벤트 선언
            this.FormClosed += Form1_FormClosing;
        }
        /// <summary>
        /// 폼 닫기 이벤트 핸들러 선언
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosedEventArgs e)
        {
            if (client != null && client.IsConnected)
            {
                client.Disconnect();
            }
        }

        /// <summary>
        /// 수신 메세지 표시
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // 수신된 메시지를 변수에 저장
            string receivedMessage = Encoding.UTF8.GetString(e.Message);

            // UI 업데이트를 위해 UI 스레드로 전달
            Invoke(new Action(() =>
            {
                // receivedMessage를 Form label ReceivedText에 표시
                ReceivedText.Text = receivedMessage;
            }));
        }
        /// <summary>
        /// start 버튼 클릭했을때 실행
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Startbutton_Click(object sender, EventArgs e)
        {
            // MQTT 브로커 주소
            string MQTT_BROKER_ADDRESS = "127.0.0.1";

            // 클라이언트 인스턴스 생성
            client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

            // 메시지 수신 시 이벤트 핸들러 등록
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            // 고유한 클라이언트 ID 생성
            string clientId = "COORONG";

            try
            {
                client.Connect(clientId);
                //연결이 성공하면 Serverconnect에 성공 메세지출력
                if (client.IsConnected) Serverconnect.Text = "SERVER " + MQTT_BROKER_ADDRESS + "와 연결 성공!";
            }
            catch (Exception ex)
            {
                //연결이 실패하면 Serverconnect에 실패 메세지, 오류메세지 출력
                Serverconnect.Text = "브로커에 연결할 수 없습니다.\n" + ex.Message + "연결 오류";
            }

            // 수신 토픽 "cookie" 구독
            client.Subscribe(new string[] { "cookie" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
        /// <summary>
        /// Send버튼 클릭했을때 실행
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sendbutton_Click(object sender, EventArgs e)
        {
            // 보낼 메시지
            string messageToSend = SendText.Text;

            // 발신 토픽 "coorong", 메세지 발송
            client.Publish("coorong", Encoding.UTF8.GetBytes(messageToSend), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);

            //메세지박스 초기화
            SendText.Text = "";
        }
    }
}

 

By Dozzing

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다