C#과 .NET MQTT 3.1.1과 5.0

MQTT 3.1.1과 5.0용 C# MQTT 클라이언트

.NET Framework 2.0부터 .NET 10까지, 이 .NET MQTT 클라이언트로 C# 앱을 TCP나 WebSocket으로 모든 MQTT 브로커에 연결하세요.

MQTT 3.1.1과 MQTT 5.0
QoS 0, 1, 2
TCP 또는 WebSocket 위의 TLS
Last Will, Retain, Keep-Alive

C#에서 연결, 구독, 게시하기 → · 가격 보기 →

C# MQTT 클라이언트
using esegece.sgcWebSockets;

var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 8883;
client.TLS = true;
client.Specifications.RFC6455 = false; // MQTT over TCP

var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.MQTTVersion = TwsMQTTVersion.mqtt5;

mqtt.OnMQTTConnect += (conn, session, code, reason, props) =>
    mqtt.Subscribe("sensors/#");
mqtt.OnMQTTPublish += (conn, topic, text, props) =>
    Console.WriteLine(topic + ": " + text);

client.Active = true;

sgcWebSockets 클라이언트 위에서 동작하는 MQTT 클라이언트

전송 컴포넌트 하나, 프로토콜 컴포넌트 하나, 모든 MQTT 패킷에 대한 이벤트.

sgcWebSockets .NET의 C# MQTT 클라이언트는 esegece.sgcWebSockets 네임스페이스의 TsgcWSPClient_MQTT예요. 소켓을 직접 열지는 않아요. TsgcWebSocketClient를 Client 속성에 지정하면, 그 클라이언트가 MQTT 패킷을 일반 TCP 스트림(포트 1883과 8883)으로, 또는 WebSocket 엔드포인트로 MQTT를 제공하는 브로커를 위해 WebSocket 프레임 안에 담아 전달해요. 호스트, 포트, TLS, 프록시, 자동 재연결은 전송 컴포넌트가 맡고, MQTT 세션, 토픽, QoS는 프로토콜 컴포넌트가 맡아요.

브로커의 모든 응답이 C# 이벤트가 돼요. OnMQTTConnect, OnMQTTPublish, OnMQTTSubscribe, OnMQTTPubAck, OnMQTTPubRec, OnMQTTPubComp, OnMQTTPing, OnMQTTDisconnect이고, MQTT 5.0 향상된 인증에는 OnMQTTAuth가 있어요. 같은 패키지가 Windows, Linux, macOS에서 .NET Framework 2.0부터 4.8.1, .NET Core 1.0부터 3.1, .NET 5부터 .NET 10, .NET Standard 1.6과 2.0을 대상으로 해요.

MQTT 3.1.1과 5.0

MQTTVersion으로 프로토콜을 선택하세요. TwsMQTTVersion.mqtt311 또는 TwsMQTTVersion.mqtt5예요.

TCP 또는 WebSocket

전송 컴포넌트에서 Specifications.RFC6455 = false이면 TCP로 원시 MQTT를 보내요. 켜 두면 WebSocket 경로로 MQTT를 터널링해요.

세 가지 QoS 수준

모든 게시와 구독에서 TmqttQoS.mtqsAtMostOnce, mtqsAtLeastOnce, mtqsExactlyOnce를 쓸 수 있어요.

세션 제어

Authentication의 사용자 이름과 비밀번호, HeartBeat의 Keep-Alive 핑, LastWillTestament의 Last Will.

C#에서 연결, 구독, 게시하기

esegece.sgcWebSockets NuGet 패키지(또는 esegece.sgcWebSockets.Community)를 설치한 다음 네 단계를 따라 하세요.

using esegece.sgcWebSockets;

// transport: TCP with TLS on the standard secure MQTT port
var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 8883;
client.TLS = true;
client.TLSOptions.Version = TwsTLSVersions.tls1_2;
client.Specifications.RFC6455 = false;   // raw MQTT, no WebSocket handshake

// protocol: MQTT 3.1.1 with credentials and keep-alive
var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.MQTTVersion = TwsMQTTVersion.mqtt311;
mqtt.Authentication.Enabled = true;
mqtt.Authentication.UserName = "device-01";
mqtt.Authentication.Password = "secret";
mqtt.HeartBeat.Enabled = true;
mqtt.HeartBeat.Interval = 30;

mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
    Console.WriteLine("#mqtt connected: " + reasonName);
mqtt.OnMQTTDisconnect += (conn, reasonCode, reasonName, props) =>
    Console.WriteLine("#mqtt disconnected: " + reasonName);

client.Active = true;
// subscribe once the broker has accepted the session
mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
{
    mqtt.Subscribe("sensors/+/temperature");
    mqtt.Subscribe("alerts/#", TmqttQoS.mtqsExactlyOnce, null);
};

mqtt.OnMQTTSubscribe += (conn, packetId, codes, props) =>
    Console.WriteLine("#subscribed, packet " + packetId);

// every message on a subscribed topic arrives here
mqtt.OnMQTTPublish += (conn, topic, text, props) =>
    Console.WriteLine(topic + " = " + text);

// stop receiving a topic
mqtt.UnSubscribe("alerts/#");
// QoS 0: fire and forget
mqtt.Publish("sensors/room1/temperature", "21.5");

// QoS 1 with the retain flag, so late subscribers get the last value
mqtt.Publish("devices/device-01/status", "online", TmqttQoS.mtqsAtLeastOnce, true);

// QoS 2: wait up to 10 seconds for the broker to confirm
bool ok = mqtt.PublishAndWait("orders/new", "{\"id\": 42}", TmqttQoS.mtqsExactlyOnce, 10000);

// binary payloads
mqtt.Publish("images/cam1", File.ReadAllBytes("frame.jpg"));

// acknowledgements
mqtt.OnMQTTPubAck  += (conn, packetId, reasonCode, reasonName, props) =>
    Console.WriteLine("#puback " + packetId);
mqtt.OnMQTTPubComp += (conn, packetId, reasonCode, reasonName, props) =>
    Console.WriteLine("#pubcomp " + packetId);
using esegece.sgcWebSockets;

// the same MQTT client, tunnelled through a secure WebSocket (wss://)
var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 443;
client.TLS = true;
client.Options.Parameters = "/mqtt";   // the broker's WebSocket path
client.WatchDog.Enabled = true;          // reconnect after network drops

var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.OnMQTTPublish += (conn, topic, text, props) => Console.WriteLine(topic + ": " + text);

client.Active = true;

.NET 다운로드의 WinForms 데모 MQTT Client와 MQTT Console은 같은 호출을 폼에 연결해 줘요. 브로커 목록, TLS와 프록시 설정, QoS와 Retain 옵션이 있어요.

C#에서 쓰는 MQTT QoS 0, 1, 2

Publish, PublishAndWait, Subscribe에 TmqttQoS 값을 전달하세요. QoS 1과 2에서는 확인 응답이 제때 도착하지 않으면 클라이언트가 메시지를 다시 보내요. 전달을 추적하려면 OnMQTTPubAck이나 OnMQTTPubComp를 처리하거나, 제한 시간(기본 10초) 안에 브로커가 응답하지 않으면 false를 반환하는 PublishAndWait를 호출하세요.

QoSC# 값전달확인 이벤트
0TmqttQoS.mtqsAtMostOnce최대 한 번, 최선의 노력, 응답 없음없음
1TmqttQoS.mtqsAtLeastOnce최소 한 번, 브로커가 확인 응답OnMQTTPubAck
2TmqttQoS.mtqsExactlyOnce정확히 한 번, 4단계 핸드셰이크OnMQTTPubRec, OnMQTTPubComp

TLS, 자격 증명, Last Will, Keep-Alive

포트 8883의 TLS

전송 컴포넌트에서 TLS = true로 설정하고 TLSOptions.Version에서 TLS 1.3까지 프로토콜을 선택하세요. 클라이언트 인증서가 필요한 브로커에는 TLSOptions가 CertFile, KeyFile, Password, RootCertFile도 받고, VerifyCertificate가 서버 인증서를 검사해요.

사용자 이름과 비밀번호

Authentication.Enabled, Authentication.UserName, Authentication.Password가 CONNECT 패킷에 들어가요.

Last Will

LastWillTestament가 Topic, Text, QoS, Retain을 설정해서, 장치가 정상적으로 연결을 끊지 않고 끊어졌을 때 브로커가 "offline" 메시지를 게시해요.

Keep-Alive

HeartBeat.Enabled와 HeartBeat.Interval이 PINGREQ 패킷을 보내고, OnMQTTPing이 각 응답을 알려 주며, Ping()은 필요할 때 하나를 보내요.

클라이언트 ID와 클린 세션

OnMQTTBeforeConnect가 CleanSession과 ClientIdentifier를 참조로 전달해서, 장치마다 영구 세션과 고정 클라이언트 ID를 선택할 수 있어요.

프록시와 재연결

전송 컴포넌트의 Proxy 설정과 WatchDog 자동 재연결이 MQTT에 그대로 적용돼요.

mqtt.LastWillTestament.Enabled = true;
mqtt.LastWillTestament.Topic = "devices/device-01/status";
mqtt.LastWillTestament.Text = "offline";
mqtt.LastWillTestament.QoS = TmqttQoS.mtqsAtLeastOnce;
mqtt.LastWillTestament.Retain = true;

mqtt.OnMQTTBeforeConnect += (TsgcWSConnection conn, ref bool cleanSession, ref string clientId) =>
{
    cleanSession = false;
    clientId = "device-01";
};

C#에서 쓰는 MQTT 5.0 기능

MQTTVersion = TwsMQTTVersion.mqtt5로 설정하면 클라이언트가 MQTT 5.0을 사용해요. 그러면 모든 확인 응답 이벤트가 패킷 속성과 함께 브로커의 ReasonCode와 ReasonName을 전달하므로, 실패가 연결 끊김이 아니라 이유와 함께 도착해요.

연결 속성

ConnectProperties가 SessionExpiryInterval, ReceiveMaximum, MaximumPacketSize, TopicAliasMaximum, UserProperties, 그리고 응답 정보와 문제 정보에 대한 요청 플래그를 설정해요.

게시 속성

요청과 응답 패턴을 위한 메시지별 ContentType, ResponseTopic, CorrelationData, MessageExpiryInterval, TopicAlias, PayloadFormat, 사용자 속성.

향상된 인증

Auth()가 AuthenticationMethod와 AuthenticationData를 담아 재인증을 포함한 AUTH 패킷을 보내고, OnMQTTAuth가 브로커의 챌린지를 받아요.

Will과 연결 해제 속성

Last Will의 Will 지연 간격과 메시지 만료, 그리고 Disconnect의 이유 코드, 이유 문자열, 세션 만료.

mqtt.MQTTVersion = TwsMQTTVersion.mqtt5;
mqtt.ConnectProperties.Enabled = true;
mqtt.ConnectProperties.SessionExpiryInterval = 3600;   // keep the session one hour
mqtt.ConnectProperties.ReceiveMaximum = 100;

mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
    Console.WriteLine("CONNACK " + reasonCode + " " + reasonName);

모든 표준 MQTT 브로커, 그리고 AWS IoT와 Azure IoT

클라이언트가 MQTT 3.1.1과 5.0 사양을 따르므로 자체 호스팅 브로커와 관리형 브로커 모두에 연결돼요. 일반 TCP는 포트 1883, TLS는 8883, HTTPS 포트만 열려 있다면 브로커의 WebSocket 경로를 쓰세요. 클라우드 IoT 플랫폼을 위해 sgcWebSockets .NET에는 AWS IoT Core용 AWS IoT 클라이언트와 Azure IoT Hub용 Azure IoT 클라이언트도 들어 있어요. 둘 다 MQTT 기반이며 .NET 기능 매트릭스에 나와 있어요.

같은 라이브러리가 AMQP 0.9.1과 1.0, STOMP, Kafka, C# WebSocket 클라이언트와 서버도 제공해서, 종속성 하나로 애플리케이션의 모든 메시징 프로토콜을 다룰 수 있어요.

무료로 시작하고, 모든 프로토콜에 하나의 가격

MQTT 클라이언트는 모든 .NET 에디션에 들어 있어요. Community는 소규모 팀(매출 EUR 1M 미만, 개발자 5명 이하)이 상업적, 비상업적 용도로 무료로 쓸 수 있고, 전체 기능과 시작 알림이 있어요. Professional은 알림이 없고 개발자당 €149부터이며 1년 업데이트가 포함돼요. Enterprise는 어셈블리를 다시 빌드할 수 있는 소스 코드를 더해요. Team과 Site 라이선스는 가격 페이지(.NET 탭)에 있어요.

C# MQTT 자주 묻는 질문

브로커의 Host와 Port로 TsgcWebSocketClient를 만들고, 일반 TCP 브로커라면 Specifications.RFC6455 = false로 설정하세요. 그다음 TsgcWSPClient_MQTT를 만들고 클라이언트를 Client 속성에 지정하세요. client.Active = true로 설정하면 연결이 열리고, 브로커가 세션을 수락하면 OnMQTTConnect가 발생해요.

네. MQTT 5.0은 MQTTVersion을 TwsMQTTVersion.mqtt5로, MQTT 3.1.1은 TwsMQTTVersion.mqtt311로 설정하세요. MQTT 5.0은 모든 확인 응답의 이유 코드, 연결 및 게시 속성, 사용자 속성, 향상된 인증을 더해 줘요.

Publish(topic, text, TmqttQoS.mtqsAtLeastOnce) 또는 TmqttQoS.mtqsExactlyOnce를 호출하세요. 필요하면 Retain 플래그를 함께 지정해요. 브로커가 메시지를 처리했는지 코드가 알아야 한다면 PublishAndWait를 쓰세요. 제한 시간 안에 응답이 없으면 false를 반환해요.

네. TsgcWebSocketClient에서 Port = 8883과 TLS = true로 설정하고, TLSOptions.Version에서 버전(TLS 1.3까지)을 선택하세요. 브로커가 클라이언트 인증서를 요구하면 TLSOptions.CertFile과 KeyFile을 추가하세요.

네, 전송 컴포넌트의 기본값이에요. Specifications.RFC6455를 켜 두고 Options.Parameters를 브로커의 WebSocket 경로(예: /mqtt)로 설정한 다음, wss://를 위해 포트 443에서 TLS = true를 쓰세요. HTTPS만 허용하는 방화벽도 MQTT가 통과할 수 있어요.

Windows, Linux, macOS의 .NET Framework 2.0부터 4.8.1, .NET Core 1.0부터 3.1, .NET 5부터 .NET 10, .NET Standard 1.6과 2.0을 지원해요. nuget.org에서 esegece.sgcWebSockets 또는 무료 esegece.sgcWebSockets.Community 패키지를 설치하세요.

네. Community 에디션에는 MQTT 클라이언트가 들어 있고, 소규모 팀(매출 EUR 1M 미만, 개발자 5명 이하)이 상업적, 비상업적 용도로 무료로 쓸 수 있으며 시작 알림이 표시돼요. 더 큰 조직은 개발자당 €149부터 시작하는 Professional이나 Enterprise를 구매하세요.

sgcWebSockets .NET 더 알아보기

C# WebSocket 라이브러리

MQTT 트래픽을 전달하는 WebSocket 클라이언트와 서버. TLS, 압축, 자동 재연결을 지원해요.

.NET 기능 매트릭스

MQTT, AMQP, STOMP, AWS IoT, Azure IoT를 포함해 .NET 에디션의 모든 컴포넌트와 프로토콜.

다운로드

Community 에디션, NuGet 패키지, MQTT Client와 MQTT Console을 포함한 컴파일된 .NET 데모.

Delphi와 C++Builder에서도 쓸 수 있어요

같은 MQTT 클라이언트를 Delphi와 C++Builder에서도 같은 TsgcWSPClient_MQTT 클래스와 이벤트로 쓸 수 있어요.

최고의 가성비: All-Access모든 eSeGeCe 제품과 프리미엄 지원이 포함되어 연 €1,059부터 이용할 수 있어요.
All-Access 가격 보기

오늘 C#으로 첫 MQTT 메시지를 게시해 보세요

체험판을 다운로드하거나 NuGet에서 esegece.sgcWebSockets.Community를 설치하세요. Professional은 개발자당 €149부터예요.