Exemplo n.º 1
0
int
Query_WordLookup(char *imageName, char *word, char *result, int result_maxsize)
{
  int sockfd = ConnectToImageServer(imageName);
  if (sockfd < 0) {
    return -1;
  }
  /*
   * We now have an open TCP connection to the server.
   * Send query and get response.
   */

  /* You need to implement this - Note the buffer size is likely wrong. */

  char buf[1024*1024];
  int nbytes = read(sockfd, buf, sizeof(buf));
  if (nbytes > 0) {

    if (nbytes > result_maxsize) {
      nbytes = result_maxsize;
    }
  }
  memcpy(result, buf, nbytes);
  close(sockfd);

  return nbytes;
}
Exemplo n.º 2
0
int
Query_WordLookup(char *imageName, void *word, char **result)
{
  int sockfd = ConnectToImageServer(imageName);
  if (sockfd < 0) {
    return -1;
  }
  /*
   * We now have an open TCP connection to the server.
   * Send query and get response.
   */

  /* Write the query */
  // Get the length of the query 
  int length;
  memcpy(&length,word,sizeof(int));
  
  // Send the query message
  int totalBytesWritten = 0;
  while(totalBytesWritten < sizeof(int)){
    char *buff = word + totalBytesWritten;
    int bytesToWrite = length + sizeof(int) - totalBytesWritten;
    int nbytes = write(sockfd,buff,bytesToWrite);
    if(nbytes < 0){
      perror("write");
      return -1;
    }
    totalBytesWritten += nbytes;
  }

  /* Read the response */
  
  // Read the length of the response
  char responseLength[sizeof(int)];
  unsigned int totalBytesRead = 0;
  while(totalBytesRead < sizeof(int)){
    char * buff = responseLength + totalBytesRead;
    unsigned int bytesToRead = sizeof(int) - totalBytesRead;
    int nbytes = read(sockfd,buff,bytesToRead);
    if(nbytes < 0){
      perror("read");
      return -1;
    }
    totalBytesRead += nbytes;
  }
  
  // Get the response length as an integer
  int len;
  memcpy(&len,responseLength,sizeof(int));
  
  // Read the response
  char *response = malloc(len+1);
  totalBytesRead = 0;
  while(totalBytesRead < len){
    char *buff = response + totalBytesRead;
    int bytesToRead = len - totalBytesRead;
    int nbytes = read(sockfd,buff,bytesToRead);
    if(nbytes < 0)return -1;
    totalBytesRead += nbytes;
  }
  close(sockfd);
  // Append the null terminator
  response[len] = 0; 
 
  *result = response;
  return totalBytesRead;
}