Receiving data from Java-Client (data contains int, short, string)

前端 未结 1 880
孤城傲影
孤城傲影 2020-12-12 05:32

I was searching for hours to get an answer about my question, but didnt find anything. Maybe I get some help here.

What I\'m trying to do: A Java-Client sends a mes

相关标签:
1条回答
  • 2020-12-12 05:55

    You need to create a generic "read_n_bytes" function.

    This you can use to read the message-size, the operation and the text, in three successive calls.

    Those three calls you then wrap in a function to be called to read an entire message.


    A generic reader might look like this:

    /*
     * Reads n bytes from sd into where p points to.
     *
     * returns 0 on succes or -1 on error.
     *
     * Note: 
     * The function's name is inspired by and dedicated to "W. Richard Stevens" (RIP).
     */
    int readn(int sd, void * p, size_t n)
    {
      size_t bytes_to_read = n;
      size_t bytes_read = 0;
    
      while (bytes_to_read > bytes_read)
      {
        ssize_t result = read(sd, p + bytes_read, bytes_to_read);
        if (-1 == result)
        {
          if ((EAGAIN == errno) || (EWOULDBLOCK == errno))
          {
            continue;
          }
    
    #     ifdef DEBUG     
          {
            int errno_save = errno;
            perror("read() failed");
            errno = errno_save;
          }
    #     endif
    
          break;
        }
        else if(0 == result)
        {
    #     ifdef DEBUG
          {     
            int errno_save = errno;
            fprintf(stderr, "%s: Connection closed by peer.", __FUNCTION__);
            errno = errno_save;
          }
    #     endif
    
          break;
        }
    
        bytes_to_read -= result;
        bytes_read += result;
      }
    
      return (bytes_read < bytes_to_read) ?-1 :0; 
    }
    
    0 讨论(0)
提交回复
热议问题