应用层协议
一、HTTP / HTTPS
1. 协议结构
GET / HTTP/1.1
Host: example.com
User-Agent: myapp/1.0
Accept: */*
响应:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1234
<html>...</html>
2. 方法
- GET / POST / PUT / DELETE / PATCH / OPTIONS / HEAD
3. 状态码
- 1xx 信息
- 2xx 成功(200、201、204)
- 3xx 重定向(301、302、304)
- 4xx 客户端错误(400、401、403、404)
- 5xx 服务器错误(500、502、503)
4. 嵌入式 HTTP 库
- libcurl:客户端
- mongoose:单文件、客户端/服务端
- civetweb:嵌入式服务端
- microhttpd:GNU
- nginx:嵌入式裁剪版(nginx + Lua)
5. libcurl 示例
#include <curl/curl.h>
CURL *c = curl_easy_init();
curl_easy_setopt(c, CURLOPT_URL, "http://example.com/api/data");
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_perform(c);
curl_easy_cleanup(c);
二、RESTful API
GET /api/sensors 列表
GET /api/sensors/1 详情
POST /api/sensors 创建
PUT /api/sensors/1 更新
DELETE /api/sensors/1 删除
GET /api/sensors/1/data?start=...&end=... 查询
POST /api/auth/login { user, pwd } 认证
三、JSON 库
- cJSON:极小、单文件
- Jansson:BSD 协议
- json-c:广泛使用
- nlohmann/json:C++
- RapidJSON:高性能
cJSON 示例
#include "cJSON.h"
char *json = "{\"name\":\"alice\",\"age\":30}";
cJSON *root = cJSON_Parse(json);
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("%s\n", name->valuestring);
cJSON_AddNumberToObject(root, "score", 95);
char *out = cJSON_Print(root);
printf("%s\n", out);
free(out);
cJSON_Delete(root);
四、MQTT(IoT 首选)
1. 概念
- 发布/订阅模式
- 三个角色:Publisher、Subscriber、Broker
- Topic 主题分层:
sensors/temperature/room1 - QoS 0/1/2
2. Broker
- Mosquitto(最常用)
- EMQ X
- HiveMQ
- AWS IoT / Azure IoT
3. 客户端库
- Eclipse Paho MQTT C/C++:跨平台
- mosquitto(libmosquitto):C
4. Paho MQTT 示例(发布)
#include "MQTTClient.h"
MQTTClient client;
MQTTClient_create(&client, "tcp://broker.hivemq.com:1883",
"my_client_id", MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
opts.keepAliveInterval = 20;
opts.cleansession = 1;
MQTTClient_connect(client, &opts);
MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = "{\"temp\":25}";
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "sensors/temperature", &pubmsg, NULL);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
5. 订阅
MQTTClient_subscribe(client, "sensors/#", 1);
// 回调
int msg_arrived(void *ctx, char *topicName, int topicLen, MQTTClient_message *msg) {
printf("topic: %s, payload: %s\n", topicName, (char*)msg->payload);
MQTTClient_freeMessage(&msg);
MQTTClient_free(topicName);
return 1;
}
MQTTClient_setCallbacks(client, NULL, NULL, msg_arrived, NULL);
五、CoAP(受限设备 HTTP)
1. 特点
- 基于 UDP
- 极小(适合 6LoWPAN、传感器)
- 资源模型
- GET/POST/PUT/DELETE
- 支持 Observe(订阅)
2. 库
- libcoap:C
- cantcoap
3. 客户端
coap_context_t *ctx = coap_new_context(NULL);
coap_address_t addr;
coap_address_init(&addr);
addr.addr.sin.sin_family = AF_INET;
addr.addr.sin.sin_port = htons(5683);
inet_pton(AF_INET, "192.168.1.10", &addr.addr.sin.sin_addr);
coap_session_t *sess = coap_new_client_session(ctx, NULL, &addr, COAP_PROTO_UDP);
coap_pdu_t *pdu = coap_new_pdu(COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET);
coap_add_option(pdu, COAP_OPTION_URI_PATH, 5, "temp");
coap_send(sess, pdu);
六、WebSocket
- HTTP 升级
- 全双工
- 嵌入式库:libwebsockets、uWebSockets
七、gRPC / Protocol Buffers
- 高性能 RPC
- Protobuf 二进制序列化
- 适合云边协同
syntax = "proto3";
service Sensor {
rpc Get(SensorRequest) returns (SensorResponse);
}
message SensorRequest { string id = 1; }
message SensorResponse { float value = 1; }
八、Modbus(工业)
- Modbus TCP / RTU
- 简单、广泛用于 PLC、传感器
九、OPC UA(工业 4.0)
- 工业物联网标准
- 信息模型 + 安全 + 服务
十、选型指南
| 场景 | 协议 |
|---|---|
| Web / REST | HTTP/JSON |
| IoT 设备云端 | MQTT / CoAP |
| 视频流 | RTSP / WebRTC |
| 文件传输 | FTP / SFTP / SCP |
| 远程登录 | SSH / Telnet |
| 时间同步 | NTP |
| DNS | DNS |
| 工业控制 | Modbus / OPC UA |
| 车内网络 | CAN / SOME/IP |
| 实时消息 | MQTT / WebSocket |