//接收端 #include #include #include #include #include #include #include #include #include using namespace std; int main() { //创建 int sockfd = socket(AF_INET, SOCK_STREAM, 0); 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 = INADDR_ANY; addr.sin_port = htons(8888); // 绑定端口号,改! if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("error"); exit(1); } if (listen(sockfd, 5) < 0) { // 监听socket perror("listen error"); exit(1); } int connfd; struct sockaddr_in cliaddr; socklen_t clilen = sizeof(cliaddr); if ((connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &clilen)) < 0) { // 接受连接 perror("accept error"); exit(1); } char buf[BUF_SIZE]; int len, count = 0; memset(buf, 0, sizeof(buf)); recv(connfd, buf, size, 0); // 接收JSON数据长度size,改! 通常是1024 len = atoi(buf); string json_str; for (int i = 0; i < len; i += BUF_SIZE) { // 分批接收JSON数据 int size = min(BUF_SIZE, len - i); recv(connfd, buf, size, 0); printf("Receive JSON packet %d\n", ++count); // 打印接收的JSON数据包编号 json_str.append(buf, size); usleep(10000); // 10ms循环 } Json::Value json_data; Json::Reader reader; if (!reader.parse(json_str, json_data)) { // 解码为JSON对象 cerr << "parse error" << endl; exit(1); } cout << "x: " << json_data["x"].asString() << endl; cout << "y: " << json_data["y"].asString() << endl; cout << "z: " << json_data["z"].asString() << endl; close(connfd); close(sockfd); return 0; }