2

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

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

使用的协议: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);
4

2 回答 2

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);
}
于 2013-08-31T19:06:38.120 回答
0

发送后尝试刷新数据。如果您将套接字与 fdopen 一起使用,则需要

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

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

更新

使 memset 脱离循环

于 2013-08-31T18:37:41.103 回答