C套接字在打印时缺少前两个字符的值

时间:2018-11-18 19:27:24

标签: c sockets recv

大家好,我正在尝试打印从服务器发送到客户端的字符串,但是当我这样做时,它缺少前两个字符。我已经为字符数组分配了足够的内存,所以我不确定这里出了什么问题。

要接收的客户端代码:

char buffer[62]; // I/O buffer 
    char phrase[100];
    char reversed[20];
    int i,m; 
    /* Receive up to the buffer size (minus 1 to leave space for
     a null terminator) bytes from the sender */
    numBytes = recv(sock, buffer, 62, 0); //recv by number of bytes of greeting string (which is 60 bytes)
    if (numBytes < 0)
      DieWithSystemMessage("recv() failed");
    else if (numBytes == 0)
      DieWithUserMessage("recv()", "connection closed prematurely");
    totalBytesRcvd += numBytes; // Keep tally of total bytes
    buffer[numBytes] = '\0';    // Terminate the string!
    printf("Received:%s ", buffer);     // Setup to print the echoed string
    numBytes = recv(sock, phrase,100, 0); //set numbytes to amount 
    if (numBytes < 0)
      DieWithSystemMessage("recv() failed");
    else if (numBytes == 0)
      DieWithUserMessage("recv()", "connection closed prematurely");
    totalBytesRcvd += numBytes; // Keep tally of total bytes
    phrase[numBytes] = '\0';    // Terminate the string!
    printf("\nShort phrase from server: %s\n",phrase);
    m = strlen(phrase); //get length of phrase
    for(i=m-1; i>=0; i--){
     sprintf(reversed,"%c",phrase[i]);
      printf("%s",reversed);

“来自服务器的简短短语”正在打印twork而不是网络

发送值的服务器代码:

void HandleTCPClient(int clntSocket) {
  char buffer[BUFSIZE]; // Buffer for echo string
  char clientIP[10];
  char clientPort[10];
  char greeting[60];
  char shortPhrase[10] = "Network";
  char reversed[10];
  // Receive message from client 39
  ssize_t numBytesRcvd = recv(clntSocket, buffer, 39, 0);
  if (numBytesRcvd < 0)
    DieWithSystemMessage("recv() failed");
    printf("first recv: %s", buffer);
   //recv client ip and assign to variable to hold
    recv(clntSocket,clientIP,10,0);
    printf("clientIP : %s\n" ,clientIP);
//recv client port and assign to variable to hold
    recv(clntSocket,clientPort,10,0);
    printf("client port : %s\n" ,clientPort);



//create greeting string to send to client
sprintf(greeting,"%s-%s Welcome to the netsvr netserver!",clientIP,clientPort); //assign myPort integer to char so we can send it

//recv client port and assign to variable to hold
   ssize_t numBytesSent = send(clntSocket, greeting, 60, 0);
    send(clntSocket,shortPhrase,10,0);

  recv(clntSocket,reversed,10,0);
  printf("reversed phrase : %s\n" ,reversed);
  // Send greeting string and receive again until end of stream
  while (numBytesRcvd > 0) { // 0 indicates end of stream
    // Echo message back to client
    // See if there is more data to receive
    numBytesRcvd = recv(clntSocket, buffer, 20, 0);
    if (numBytesRcvd < 0)
    DieWithSystemMessage("recv() failed");


  }

close(clntSocket); // Close client socket
}

0 个答案:

没有答案