本人转载。
mosquitto_pub&mosquitto_sub
在实现MQTT client之前,我们可以先使用mosquitto_pub和mosquitto_sub模拟,MQTT的发布和订阅
fflush( stdout );
mbedtls_entropy_init( &entropy );
if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *) pers,
strlen( pers ) ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret );
goto exit;
}
mbedtls_printf( " ok\n" );
加载证书
ret = mbedtls_x509_crt_parse_file( &cacert, "./cacert.pem");
if( ret <0 )
{
mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse returned -0x%x\n\n", -ret );
goto exit;
}
mbedtls_printf( " ok (%d skipped)\n", ret );
ret &#61; mbedtls_x509_crt_parse_file( &clicert, "./client.crt");
if( ret !&#61; 0 )
{
mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse returned %d\n\n", ret );
goto exit;
}
ret &#61; mbedtls_pk_parse_keyfile( &pkey, "./client.key", "123456");
if( ret !&#61; 0 )
{
mbedtls_printf( " failed\n ! mbedtls_pk_parse_key returned %d\n\n", ret );
goto exit;
}
mbedtls_pk_parse_keyfile 第三个参数是生成客户端证书&#xff0c;自己输入的密钥
建立TCP连接
/*
* 1. Start the connection
*/
mbedtls_printf( " . Connecting to tcp/%s/%s...", SERVER_NAME, SERVER_PORT );
fflush( stdout );
if( ( ret &#61; mbedtls_net_connect( &server_fd, SERVER_NAME,
SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) !&#61; 0 )
{
mbedtls_printf( " failed\n ! mbedtls_net_connect returned %d\n\n", ret );
goto exit;
}
TLS握手
/*
* 4. Handshake
*/
mbedtls_printf( " . Performing the SSL/TLS handshake..." );
fflush( stdout );
while( ( ret &#61; mbedtls_ssl_handshake( &ssl ) ) !&#61; 0 )
{
if( ret !&#61; MBEDTLS_ERR_SSL_WANT_READ && ret !&#61; MBEDTLS_ERR_SSL_WANT_WRITE )
{
mbedtls_printf( " failed\n ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret );
goto exit;
}
}
mbedtls_printf( " ok\n" );
握手阶段结束&#xff0c;就完成了TLS连接&#xff0c;开始加密通讯&#xff0c;下面就是应用层MQTT的连接
MQTT连接
mbedtls_printf(" \n.....................mqtttenter.....................\n" );
PTmqtttenter();
mqtt_connect((mqtt_broker_handle_t *)PTMqttGetBroker());
mbedtls_printf( "\n....................mqtt_connect.....................\n" );
mqtt_subscribe((mqtt_broker_handle_t *)PTMqttGetBroker(), MQTTSUBTOPIC, 0);
mqtt_publish((mqtt_broker_handle_t *)PTMqttGetBroker(), MQTTPUBTOPIC, test, strlen(test), 0);
这样就完成MQTT的连接&#xff0c;我们来看下实际效果
如上图&#xff0c;我发送的MQTT消息&#xff0c;主题为mtopic 消息为test_cfd
订阅的终端&#xff0c;可以成功收到消息。
注意&#xff1a;程序运行加载的证书是在工程目录下&#xff0c;并且需要各位根据自己生成的客户端证书进行相应的替换。