Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

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

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 message to a C-Server. The message contains different types like integer, short and also a string (e.g. message = int: total_msg_length; short: operation; string: hello --> total_msg-length=4 (size of integer), operation = 2 (size of short), hello = 5 (each letter is 1 byte=5).

So, how can I receive the message in my server? The code below receives an Integer (works fine). Next step will be to receive a short and then a string (converted in US-ASCII).

int *msg;
int recv_size;
int final_msg;

if( (recv_size = recv(client_socket, &msg, sizeof(msg), 0 )) < 0 ){
    error_exit("Fehler bei recv(message_len)");
}

final_msg = endian_swap(msg);
printf("Message: %d
", final_msg);

return final_msg;

Is there a way to use a byte array instead of char buffer? Im thankful for every help. Please excuse my bad english, I'm from germany :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...