I want to send the data in JSON over sockets in a server-client application written in C.
I am using json-c / libjson library for handling JSON data
1) jobj is a pointer, so when you use
write(fd, jobj, sizeof(jobj))
you're writing a pointer to that object, not that object.
3) Same as before.
Maybe you should try sending it with something like
if (write(fd, jobj, sizeof(*jobj)) == -1)
/* error handler /*
On the receive side, you should do a for loop, like
for (;;)
{
r = read(fd, jobj, SIZE);
if (r == -1)
/*error handler*/
if (r == 0)
break;
}
if you know the maximum SIZE of the json, or combine malloc() and realloc() otherwise
EDIT:
I did this, and now it works fine.
client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
/* all previous code until
printf("Size of string- %lu\n", sizeof(json_object_to_json_string(jobj)))*/
char temp_buff[MAX_SIZE];
if (strcpy(temp_buff, json_object_to_json_string(jobj)) == NULL)
{
perror("strcpy");
return EXIT_FAILURE;
}
if (write(fd, temp_buff, strlen(temp_buff)) == -1)
{
perror("write");
return EXIT_FAILURE;
}
printf("Written data\n");
return EXIT_SUCCESS;
}
server.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
/* all previous code until
printf("Reading from client\n"); */
ssize_t r;
char buff[MAX_SIZE];
for (;;)
{
r = read(connfd, buff, MAX_SIZE);
if (r == -1)
{
perror("read");
return EXIT_FAILURE;
}
if (r == 0)
break;
printf("READ: %s\n", buff);
}
return EXIT_SUCCESS;
}
MAX_SIZE is a macro that specifies the maximum buffer length, set it as you wish.
Please next time paste ALL your code (including the #include ...
) and indent it properly.