#include #include #include #include #include #include #include #include #include #define BUF_SIZE 1024 // JSON数据分片大小,对应的是接收端的那个size using namespace std; int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建socket if (sockfd < 0) { perror("socket error"); exit(1); } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 目的主机IP addr.sin_port = htons(8888); // 目的主机端口号 if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { // 连接目标主机 perror("connect error"); exit(1); } Json::Value json_data; json_data["x"] = 0"; json_data["y"] = "1"; json_data["z"] = "1"; string json_str = json_data.toStyledString(); // 编码 char buf[BUF_SIZE]; int len = json_str.length(), count = 0; sprintf(buf, "%d", len); send(sockfd, buf, strlen(buf), 0); for (int i = 0; i < len; i += BUF_SIZE) { int size = min(BUF_SIZE, len - i); memcpy(buf, json_str.c_str() + i, size); send(sockfd, buf, size, 0); printf("Send JSON packet %d\n", ++count); usleep(10000); // 10msxunhuan } close(sockfd); return 0; }