# 示例代码|Examples ## 1. 基本Web服务器 ```c #include "netleaf.h" int main() { nl_web_server_t* server = nl_web_create(8080); nl_web_add_html(server, "/", "

Hello World

"); nl_web_start(server); while (1) sleep(1); return 0; } ``` ## 2. 变量硬编码 ```c #include "netleaf.h" int main() { nl_web_server_t* server = nl_web_create(8080); // 设置UTF-8编码 nl_web_set_encoding(server, "UTF-8"); // 用户信息 const char* vars[] = {"name", "user_id", "role"}; const char* values[] = {"张三", "1001", "管理员"}; nl_web_add_html_with_vars(server, "/user", "\n" "\n" "用户资料\n" "\n" "

{{name}}

\n" "

ID: {{user_id}}

\n" "

角色: {{role}}

\n" "", vars, values, 3); nl_web_start(server); while (1) sleep(1); return 0; } ``` ## 3. Vue页面带变量 ```c #include "netleaf.h" int main() { nl_web_server_t* server = nl_web_create(8080); const char* vars[] = {"company", "year"}; const char* values[] = {"NetLeaf科技", "2024"}; nl_web_add_vue_with_vars(server, "/dashboard", "

{{company}} - 管理面板

\n" "

年份: {{year}}

\n" "
\n" " \n" " {{ count }}\n" " \n" "
", vars, values, 2); nl_web_start(server); while (1) sleep(1); return 0; } ``` ## 4. 日志系统 ```c #include "netleaf.h" int main() { // 启用调试模式 nl_debug_enable(1); // 输出日志 nl_log_debug("调试信息 - 服务器启动"); nl_log_info("一般信息 - 配置加载成功"); nl_log_warn("警告 - 内存使用率偏高"); nl_log_error("错误 - 连接失败"); return 0; } ``` ## 5. 快捷函数 ```c #include "netleaf.h" int main() { nl_web_server_t* server = nl_web_create(8080); // 一行代码添加首页 nl_serve_html(0, "

Hello World

"); nl_web_start(server); while (1) sleep(1); return 0; } ``` ## 6. 编码动态适配 ```c #include "netleaf.h" int main() { // 创建服务器 nl_web_server_t* server = nl_web_create(8080); // 启用自动编码协商(见人说人话,见鬼说鬼话) nl_web_enable_auto_encoding(server, 1); // 设置回退编码(客户端未指定时使用) nl_web_set_fallback_encoding(server, "UTF-8"); // 添加页面(内部始终使用UTF-8) nl_web_add_html(server, "/", "

你好,世界!

"); // 添加JSON响应(自动转码) nl_web_add_json(server, "/api/data", "{\"message\": \"你好世界\"}"); // 服务器会自动根据客户端Accept-Charset头转换编码 // 例如:GBK客户端会收到GBK编码的响应 while (1) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } return 0; } ``` ## 8. 编码转换 ```c #include "netleaf.h" #include int main() { const char* utf8_str = "你好世界"; // UTF-8转GBK char* gbk_str = nl_encoding_convert(utf8_str, strlen(utf8_str), "UTF-8", "GBK"); printf("GBK: %s\n", gbk_str); free(gbk_str); // 自动检测编码 const char* detected = nl_encoding_detect(utf8_str, strlen(utf8_str)); printf("检测到编码: %s\n", detected); // 获取系统默认编码 const char* sys_enc = nl_encoding_get_system_default(); printf("系统默认编码: %s\n", sys_enc); return 0; } ``` ## 9. TLS 加密通信 ```c #include "netleaf_tls.h" #include int main() { // 初始化 TLS nl_tls_init(); // 创建 TLS 上下文 nl_tls_ctx_t* ctx = nl_tls_create(); if (!ctx) { printf("Failed to create TLS context\n"); return 1; } // 配置 TLS nl_tls_config_t cfg = {0}; cfg.protocol = NL_TLS_PROTOCOL_TLSV1_2; cfg.verify_peer = 1; // 加载 CA 证书 cfg.ca_chain = "ca.crt"; // 配置密码套件 cfg.ciphers = "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256"; int ret = nl_tls_configure(ctx, &cfg); if (ret != NL_OK) { printf("TLS configure failed: %s\n", nl_tls_strerror(ret)); } // 建立连接 int sock = socket(AF_INET, SOCK_STREAM, 0); // ... 连接服务器代码 ... ret = nl_tls_handshake(ctx, sock); if (ret != NL_OK) { printf("TLS handshake failed: %s\n", nl_tls_strerror(ret)); } // 安全通信 const char* msg = "Hello, TLS!"; nl_tls_send(ctx, msg, strlen(msg)); char buf[256]; nl_tls_recv(ctx, buf, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; printf("Received: %s\n", buf); // 获取对端证书信息 const char* peer_cert = nl_tls_get_peer_cert(ctx); if (peer_cert) { printf("Peer cert: %s\n", peer_cert); } // 清理 nl_tls_close(ctx); nl_tls_destroy(ctx); nl_tls_shutdown(); return 0; } ``` ## 10. MQTT 基础使用 ```c #include "netleaf_mqtt.h" #include // 消息回调函数 void on_message(void* userdata, const nl_mqtt_msg_t* msg) { printf("[Received] Topic: %s, Payload: %.*s\n", msg->topic, (int)msg->payload_len, (char*)msg->payload); } int main() { // 初始化 MQTT nl_mqtt_init(); // 创建 MQTT 客户端 nl_mqtt_client_t* client = nl_mqtt_create(); if (!client) { printf("Failed to create MQTT client\n"); return 1; } // 设置连接选项 nl_mqtt_connect_opts_t opts = {0}; opts.client_id = "netleaf-client-001"; opts.keep_alive = 60; opts.clean_session = 1; opts.username = "user"; opts.password = "password"; // 连接 MQTT 服务器 int ret = nl_mqtt_connect(client, "tcp://broker.hivemq.com:1883", &opts); if (ret != NL_OK) { printf("MQTT connect failed\n"); nl_mqtt_destroy(client); return 1; } // 订阅主题 nl_mqtt_subscribe(client, "test/topic", NL_MQTT_QOS_1, NULL); // 设置消息回调 nl_mqtt_set_msg_callback(client, on_message, NULL); // 发布消息 nl_mqtt_pub_opts_t pub_opts = {0}; pub_opts.qos = NL_MQTT_QOS_1; pub_opts.retain = 0; nl_mqtt_publish(client, "test/topic", "Hello MQTT!", 13, &pub_opts); // 保持运行 while (1) { nl_mqtt_loop(client, 1000); } // 清理 nl_mqtt_disconnect(client); nl_mqtt_destroy(client); nl_mqtt_shutdown(); return 0; } ``` ## 11. MQTT 使用 TLS 加密 ```c #include "netleaf_mqtt.h" #include "netleaf_mqtt_tls.h" #include int main() { // 初始化 MQTT 和 TLS nl_mqtt_init(); nl_mqtt_tls_init(); // 创建 MQTT 客户端 nl_mqtt_client_t* client = nl_mqtt_create(); // 设置连接选项(使用 TLS) nl_mqtt_connect_opts_t opts = {0}; opts.client_id = "netleaf-mqtt-tls"; opts.keep_alive = 60; opts.ssl_enabled = 1; // 配置 TLS nl_mqtt_tls_config_t tls_cfg = {0}; tls_cfg.ca_chain = "ca.crt"; tls_cfg.client_cert = "client.crt"; tls_cfg.client_key = "client.key"; tls_cfg.verify_peer = 1; // 连接 TLS 加密的 MQTT 服务器 int ret = nl_mqtt_connect(client, "ssl://broker.hivemq.com:8883", &opts); if (ret != NL_OK) { printf("MQTT over TLS connect failed\n"); } // 正常订阅和发布... nl_mqtt_subscribe(client, "secure/topic", NL_MQTT_QOS_1, NULL); // 心跳循环 while (1) { nl_mqtt_loop(client, 1000); } nl_mqtt_disconnect(client); nl_mqtt_tls_shutdown(); nl_mqtt_destroy(client); nl_mqtt_shutdown(); return 0; } ``` ## 12. MQTT v5.0 属性使用 ```c #include "netleaf_mqtt.h" #include int main() { nl_mqtt_init(); nl_mqtt_client_t* client = nl_mqtt_create(); // 设置 MQTT 5.0 连接属性 nl_mqtt_connect_opts_t opts = {0}; opts.client_id = "mqtt5-client"; opts.session_expiry_interval = 3600; // 会话保持1小时 opts.receive_maximum = 100; // 最大并发包数 opts.maximum_packet_size = 4096; // 最大包大小 opts.topic_alias_maximum = 10; // 主题别名最大值 // 设置用户属性 nl_mqtt_user_property_add(&opts.user_properties, "key1", "value1"); nl_mqtt_user_property_add(&opts.user_properties, "key2", "value2"); nl_mqtt_connect(client, "tcp://broker.hivemq.com:1883", &opts); // 发布消息带属性 nl_mqtt_pub_opts_t pub_opts = {0}; pub_opts.qos = NL_MQTT_QOS_1; pub_opts.payload_format_indicator = 1; // UTF-8 编码 pub_opts.message_expiry_interval = 86400; // 消息24小时后过期 pub_opts.content_type = "application/json"; pub_opts.response_topic = "response/topic"; nl_mqtt_user_property_add(&pub_opts.user_properties, "author", "netleaf"); nl_mqtt_publish(client, "test/mqtt5", "{\"data\":\"hello\"}", 20, &pub_opts); nl_mqtt_destroy(client); nl_mqtt_shutdown(); return 0; } ```