You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Conception/发送端.h

57 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <json/json.h>
#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;
}