客户端在套接字上的服务器关闭连接之前打印半数据

时间:2013-08-31 18:27:24

标签: c sockets client-server

我有这种情况。我正在尝试在C中使用套接字来发送和接收数据。客户端发送一些字符串,服务器操纵它,将其发送回客户端。一切都很好,但一个小问题是:客户端只收到服务器的第一行,显示它然后停止,直到超时后服务器关闭连接。虽然server发送的字节数=客户端收到的字节数。连接关闭后,客户端将显示其余字符串。

我想知道你的想法和可能的问题。如果您有任何问题,请告诉我。

使用的协议:TCP

以下是服务器的代码:

for (;;)
    {
            n=recv(s, buf, RBUFLEN-1, 0);
        if (n < 0)
        {
            printf("Read error\n");
            closesocket(s);
            printf("Socket %d closed\n", s);
            break;
        }
        else if (n==0)
        {
            printf("Connection closed by party on socket %d\n",s);
            closesocket(s);
            break;
        }
        else
        {
            printf("Received line from socket %03d : \n",s);
            printf("N bytes received: %d \n",n);
                     // DoSomeOperationsOnTheData() 
                 if(send(s, buffer, n, 0) != n)
            printf("Write error while replying\n");
        else
        {
            printf("Reply sent: %d bytes\n",n);
        }
    }

客户代码:

do
   {
    memset(buffer,0x0,BUFFER_SIZE);    //  init line
        rc = read(sd, buffer, BUFFER_SIZE);
        printf("\nReceived bytes: %d", rc);
        if( rc > 0)
        {
            printf("%s",buffer);
            size +=rc;
        }
    }while(rc>0);

    printf("\n   Total recieved response bytes: %d\n",size);

    close(sd);

2 个答案:

答案 0 :(得分:1)

do
{
  memset(buffer, 0, BUFFER_SIZE);    //  init line
  rc = read(sd, buffer, BUFFER_SIZE);
  printf("\nReceived bytes: %d", rc);
  if( rc > 0)
  {
    printf("%s",buffer);
    size +=rc;
  }
}while(rc>0);

应该是:

memset(buffer,0x0,BUFFER_SIZE);    //  init line
size_t size = 0;
size_t toread = BUFFER_SIZE;
do
{
  ssize_t rc = read(sd, buffer+size, toread);

  if (rc > 0)
  {
    printf("\nReceived bytes:%zd", rc);
    printf("%s", buffer);
    size += rc;
    toread -= rc;
  }
  else if (rc == 0)
  {
    printf("The server hung up.\");
    break;
  }
  else
  {
    perror("read() failed");
    break;
  }
} while (toread);

if (toread < BUFFERSIZE)
{
  printf("Warning: Read less bytes (%zu) then expected (%d).\n", toread, BUFFERSIZE);
}

答案 1 :(得分:0)

发送后尝试刷新数据。 如果你使用带有fdopen的套接字

,它需要它
FILE *fdsock = fdopen(sock, "a+");
...
fwrite(fdsock, 1, 1 "A");
fflush(fdsock);
...
fclose(fdsock);

并完成套接字,以shutdown(sock, SD_SEND);

结束

<强>更新

将memset从循环中取出