C++怎么使用#include <nlohmann/json.hpp>创建TCP通讯并传输和接收json数据
时间: 2024-01-21 07:19:35 浏览: 132
使用C++创建TCP通讯可以使用socket库,而传输和接收json数据可以使用nlohmann/json库。下面是基本的代码示例:
发送端:
```cpp
#include <iostream>
#include <string>
#include <nlohmann/json.hpp>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using json = nlohmann::json;
int main() {
// 创建socket
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
std::cerr << "socket creation failed" << std::endl;
return 1;
}
// 设置服务器地址和端口号
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(12345);
// 连接服务器
if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
std::cerr << "connection failed" << std::endl;
return 1;
}
// 构造json数据
json j;
j["name"] = "Alice";
j["age"] = 20;
std::string json_str = j.dump();
// 发送数据
if (send(sock, json_str.c_str(), json_str.size(), 0) == -1) {
std::cerr << "send failed" << std::endl;
return 1;
}
// 关闭socket
close(sock);
return 0;
}
```
接收端:
```cpp
#include <iostream>
#include <string>
#include <nlohmann/json.hpp>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using json = nlohmann::json;
int main() {
// 创建socket
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
std::cerr << "socket creation failed" << std::endl;
return 1;
}
// 设置本机地址和端口号
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = htons(12345);
// 绑定socket
if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1) {
std::cerr << "bind failed" << std::endl;
return 1;
}
// 监听socket
if (listen(sock, SOMAXCONN) == -1) {
std::cerr << "listen failed" << std::endl;
return 1;
}
// 接收连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_sock = accept(sock, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_sock == -1) {
std::cerr << "accept failed" << std::endl;
return 1;
}
// 接收数据
char buffer[1024];
int length = recv(client_sock, buffer, sizeof(buffer), 0);
if (length == -1) {
std::cerr << "receive failed" << std::endl;
return 1;
}
// 解析json数据
std::string json_str(buffer, length);
json j = json::parse(json_str);
// 输出数据
std::cout << "name: " << j["name"].get<std::string>() << std::endl;
std::cout << "age: " << j["age"].get<int>() << std::endl;
// 关闭socket
close(client_sock);
close(sock);
return 0;
}
```
上面的代码示例中,发送端使用nlohmann/json库构造json数据,并使用socket库发送数据;接收端使用socket库接收数据,并使用nlohmann/json库解析json数据。
阅读全文