添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
int sockfd = socket (AF_INET, SOCK_STREAM, 0 ); if (sockfd == -1 ) { std::cerr << "Unable to create socket" << std::endl; return -1 ; // 获取服务器地址和端口号 struct addrinfo hints; struct addrinfo * server_addrinfo; std:: memset (&hints, 0 , sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; int status = getaddrinfo (SERVER_HOSTNAME, SERVER_PORT, &hints, &server_addrinfo); if (status != 0 ) { std::cerr << "Unable to get address info for server: " << gai_strerror (status) << std::endl; return -1 ; // 连接到服务器 if ( connect (sockfd, server_addrinfo->ai_addr, server_addrinfo->ai_addrlen) == -1 ) { std::cerr << "Unable to connect to server" << std::endl; return -1 ; // 创建 JSON 对象并序列化为字符串 json j = { { "name" , "Alice" }, { "age" , 30 }, { "isMarried" , true } std::string json_str = j. dump (); // 发送 JSON 字符串到服务器 int bytes_sent = send (sockfd, json_str. c_str (), json_str. length (), 0 ); if (bytes_sent == -1 ) { std::cerr << "Unable to send data to server" << std::endl; return -1 ; // 关闭套接字 close (sockfd); return 0 ;

需要注意,以上代码仅为基本示例,并未处理错误或异常情况。在真实场景中,还需要考虑错误处理和异常情况。

  • chenhongdong Canvas
  •