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 j = {
{
"name"
,
"Alice"
},
{
"age"
,
30
},
{
"isMarried"
,
true
}
std::string json_str = j.
dump
();
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
;
需要注意,以上代码仅为基本示例,并未处理错误或异常情况。在真实场景中,还需要考虑错误处理和异常情况。