要连接到 MQTT 服务器,您必须首先创建一个 TsgcWebSocketClient 和一个 TsgcWSPClient_MQTT。然后您必须将 MQTT 组件附加到 WebSocket 客户端。
使用 WebSocket 协议连接到 Mosquitto MQTT 服务器。连接后订阅主题:"topic1"。
oClient := TsgcWebSocketClient.Create(nil);
oClient.Host := 'test.mosquitto.org';
oClient.Port := 8080;
oMQTT := TsgcWSPClient_MQTT.Create(nil);
oMQTT.Client := oClient;
oClient.Active := True;
procedure OnMQTTConnect(Connection: TsgcWSConnection; const Session: Boolean; const ReasonCode: Integer;
const ReasonName: string; const ConnectProperties: TsgcWSMQTTCONNACKProperties);
begin
oMQTT.Subscribe('topic1');
end;
MQTT 需要客户端标识符来标识客户端连接。组件会自动设置一个随机值,但如有需要,您也可以设置自己的客户端标识符。为此,只需处理 OnBeforeConnect 事件并在 aClientIdentifier 参数中设置您的值。
procedure OnMQTTBeforeConnect(Connection: TsgcWSConnection; var aCleanSession: Boolean;
var aClientIdentifier: string);
begin
aClientIdentifier := 'your client id';
end;
某些服务器需要用户名和密码才能授权 MQTT 连接。在连接服务器之前,使用 Authentication 属性设置用户名和密码的值。
oMQTT := TsgcWSPClient_MQTT.Create(nil);
oMQTT.Authentication.Enabled := True;
oMQTT.Authentication.UserName := 'your user';
oMQTT.Authentication.Password := 'your password';