gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:47 25 4
gpt4 key购买 nike

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

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

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

最佳答案

这个

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

关于客户端在连接被服务器关闭之前在套接字上打印一半数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com