【问题标题】:send and receive JSON over sockets in server and client application in C在 C 中通过服务器和客户端应用程序中的套接字发送和接收 JSON
【发布时间】:2018-08-16 07:27:39
【问题描述】:

我想通过服务器-客户端中的套接字以 JSON 格式发送数据 用 C 编写的应用程序。

我正在使用 json-c / libjson 库来处理 C 中的 JSON 数据 应用。

通过学习一些教程,我能够创建 JSON 对象并成功解析它。

现在我想使用JSON数据格式进行服务器-客户端的通信。

这是我的服务器和客户端代码的一部分

server.c

int main()
{
   int listenfd = 0, connfd = 0;    //related with the server
   struct sockaddr_in serv_addr;

   //json_object * jobj;
   uint8_t buf[158], i;

   memset(&buf, '0', sizeof(buf));
   listenfd = socket(AF_INET, SOCK_STREAM, 0);

   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   serv_addr.sin_port = htons(8888); 

   bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
   printf("binding\n");

   listen(listenfd, 5);
   printf("listening\n");
   connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

   printf("Reading from client\n");

   while ( (read(connfd, buf, 157)) > 0 )
   {
      for ( i = 0; i < 157; i++ )
         //printf("%s\n", json_object_to_json_string(jobj));
         //json_parse(jobj);
         printf("%d\n", buf[i]);
   }

   return 0;
}

client.c

int main()
{ 
    char* str;
    int fd = 0;
    struct sockaddr_in demoserverAddr;

    fd = socket(AF_INET, SOCK_STREAM, 0);

    if (fd < 0)
    {
        printf("Error : Could not create socket\n");
        return 1;
    }
    else
    {
        demoserverAddr.sin_family = AF_INET;
        demoserverAddr.sin_port = htons(8888);
        demoserverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
        memset(demoserverAddr.sin_zero, '\0', sizeof(demoserverAddr.sin_zero));
    }

    if (connect(fd, (const struct sockaddr *)&demoserverAddr, sizeof(demoserverAddr)) < 0)
    {
         printf("ERROR connecting to server\n");
         return 1;
    }

    /*Creating a json object*/
    json_object *jobj = json_object_new_object();

    /*Creating a json string*/
    json_object *jstring = json_object_new_string("Joys of Programming");

    /*Creating a json integer*/
    json_object *jint = json_object_new_int(10);

    /*Creating a json boolean*/
    json_object *jboolean = json_object_new_boolean(1);

    /*Creating a json double*/
    json_object *jdouble = json_object_new_double(2.14);

    /*Creating a json array*/
    json_object *jarray = json_object_new_array();

    /*Creating json strings*/
    json_object *jstring1 = json_object_new_string("c");
    json_object *jstring2 = json_object_new_string("c++");
    json_object *jstring3 = json_object_new_string("php");

    /*Adding the above created json strings to the array*/
    json_object_array_add(jarray,jstring1);
    json_object_array_add(jarray,jstring2);
    json_object_array_add(jarray,jstring3);

    /*Form the json object*/
    /*Each of these is like a key value pair*/
    json_object_object_add(jobj,"Site Name", jstring);
    json_object_object_add(jobj,"Technical blog", jboolean);
    json_object_object_add(jobj,"Average posts per day", jdouble);
    json_object_object_add(jobj,"Number of posts", jint);
    json_object_object_add(jobj,"Categories", jarray);

    printf("Size of JSON object- %lu\n", sizeof(jobj));
    printf("Size of JSON_TO_STRING- %lu,\n %s\n", sizeof(json_object_to_json_string(jobj)), json_object_to_json_string(jobj));

    //printf("Size of string- %lu\n", sizeof(json_object_to_json_string(jobj)));
    write(fd, json_object_to_json_string(jobj), 157);

    printf("Written data\n");
    return 0;
}

我想将 json_object jobj 从客户端发送到服务器。 如何做到这一点?

我尝试过的一些事情:

  1. 当我使用write(fd, jobj, sizeof(jobj))时,当我在服务器上接收数据时,客户端只发送8个字节,其他字符为空。

  2. 我只能在使用 write(fd, json_object_to_json_string(jobj), 157) 时发送完整的 json_object jobj,其中 157 是该 jobj 对象中的字符总数。

  3. 在服务器端,如果我使用read(connfd, jobj, sizeof(jobj)),那么我只能接收 8 个字节(在客户端,我使用的是write(fd, jobj, sizeof(jobj)))。

  4. 如果我使用上面的 server.c,我能够接收完整的 JSON 对象(如果我已经知道该对象中的字符数)。但它是原始格式(逐字节接收)。

如何从客户端发送完整的json_object jobj?

以及如何在服务器端接收完整的json_object jobj?

【问题讨论】:

  • write(fd, jobj, sizeof(jobj)) -> write(fd, jobj, sizeof(*jobj))
  • @kkk 感谢您的回复。它给出了一个错误:取消引用指向不完整类型 write(fd, jobj, sizeof(*jobj));

标签: c json sockets


【解决方案1】:

1) jobj 是一个指针,所以当你使用

write(fd, jobj, sizeof(jobj))

你正在写一个指向那个对象的指针,而不是那个对象。

3) 和以前一样。

也许你应该尝试用类似的东西发送它

if (write(fd, jobj, sizeof(*jobj)) == -1)
    /* error handler /*

在接收端,你应该做一个 for 循环,比如

for (;;)
{
    r = read(fd, jobj, SIZE);

    if (r == -1)
        /*error handler*/
    if (r == 0)
        break;
}

如果你知道 json 的最大 SIZE,或者结合 malloc()realloc() 否则

编辑:

我做了这个,现在它工作正常。

client.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

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 是一个指定最大缓冲区长度的宏,你可以随意设置。 请下次粘贴所有代码(包括#include ...)并正确缩进。

【讨论】:

  • 给出错误:取消引用指向不完整类型 write(fd, jobj, sizeof(*jobj));
  • 因为他不知道struct json_object。您可以: 1) 在库中找到它并将其粘贴到您的文件 .c 中 2) 使用 json_object_to_json_string() 函数。我认为 2) 更准确,因为它是为此目的编写的库函数。
  • 感谢您的回复。 printf("Size of JSON_TO_STRING- %lu\n ", sizeof(*json_object_to_json_string(jobj)) 输出为 Size of JSON_TO_STRING- 1; 我不知道它是否正确,我使用了 write(fd, json_object_to_json_string(jobj), sizeof (*json_object_to_json_string(jobj))); 写入 JSON 对象。在服务器上,我假设最大大小为 200 字节并使用 r = read(connfd, jobj, 200); 但 a.out 因分段错误而崩溃(核心转储) 错误。
  • @igng 感谢您的回复我还没有检查它,但我可以看到你建议从客户端逐字节发送,并在服务器端逐字节接收;是否可以将数据作为 JSON 对象接收?
  • 如果我明白你在问什么,这正是我在上面所做的。 JSON 被放入一个字符串中,然后通过套接字传递。如果 client.c 写入 { "Site Name": "Joys of Programming", "Technical blog": true, "Average posts per day": 2.140000, "Number of posts": 10 , "Categories": [ "c", "c++", "php" ] },然后 server.c 将读取 { "Site Name": "Joys of Programming ", "技术博客": true, "平均每天发帖数": 2.140000, "发帖数": 10, "类别": [ "c", "c++", "php" ] }跨度>
【解决方案2】:

要使用 TCP 套接字消息,您需要客户端和服务器学习如何解释消息。

例如,HTTP 使用 2 个字符 \r\n 作为消息的结尾 另一种选择是在消息之前发送消息的大小。

这是一个使用 JSON Jansson 库的解决方案。 它将大小添加为一个字符序列(例如“123”,后来被解析为整数 123),添加字符“#”作为大小标题的结尾,然后是 JSON 对象的 JSON 文本表示(由 Jansson 库定义) )

size_t socket_t::write(json_t *json)
{
  char *buf_json = NULL;
  std::string buf_send;
  size_t size_json;

  //get char* from json_t
  buf_json = json_dumps(json, JSON_PRESERVE_ORDER);
  size_json = strlen(buf_json);
  //construct send buffer, adding a header with size in bytes of JSON and # terminator
  buf_send = std::to_string(static_cast<long long unsigned int>(size_json));
  buf_send += "#";
  buf_send += std::string(buf_json);

  this->write(buf_send.data(), buf_send.size());

  free(buf_json);
  return buf_send.size();
}

阅读完毕

json_t * socket_t::read()
{
  int recv_size; // size in bytes received or -1 on error 
  const int size_buf = 20;
  char buf[size_buf];

  //peek header
  if ((recv_size = recv(m_socket, buf, size_buf, MSG_PEEK)) == -1)
  {
    std::cout << "recv error: " << strerror(errno) << std::endl;
  }

  //get size of JSON message
  std::string str(buf);
  size_t pos = str.find("#");
  std::string str_header(str.substr(0, pos));

  //parse header
  if ((recv_size = recv(m_socket, buf, str_header.size() + 1, 0)) == -1)
  {
    std::cout << "recv error: " << strerror(errno) << std::endl;
  }

  //sanity check
  buf[recv_size - 1] = '\0';
  assert(str_header.compare(buf) == 0);

  size_t size_json = static_cast<size_t>(std::stoull(str_header));
  std::string str_buf = read_all(size_json);
  //terminate buffer with size
  std::string str_json = str_buf.substr(0, size_json);

  //construct JSON
  json_error_t *err = NULL;
  json_t *json = json_loadb(str_json.data(), str_json.size(), JSON_PRESERVE_ORDER, err);
  return json;
}

这是在

中实现的

https://github.com/pedro-vicente/lib_netsockets

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2017-11-04
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2017-01-08
    • 2023-03-17
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多