gpt4 book ai didi

c++ - 读取和写入套接字

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:58:43 24 4
gpt4 key购买 nike

我制作了一个简单的 tcp 服务器/客户端应用程序,其中客户端向服务器写入内容,然后将其回显给客户端。但是,当我尝试读取服务器在客户端回显的内容时遇到了一些问题。

string s;
while((n = read(socketFD[0],readBuf, BUFFER_SIZE)) > 0){
cout<<"\nBytes read: "<<n<<endl;
s.append(readBuf, n);
}
cout<<"\nTest after read\n";

我向服务器写入了 16 KB 的文本。当我在客户端阅读时,我一次阅读 4 KB。

这段代码的输出是:

Bytes read: 4096

Bytes read: 4096

Bytes read: 4096

Bytes read: 4046

读取调用似乎在完成从套接字的读取后阻塞并且永远不会离开循环。我该如何解决这个问题?

编辑:这是服务器中处理连接客户端的代码。

if((childpid = fork()) == 0){
close(listenFD);
while ((n = read(connectFD, buf, BUFFSIZE)) > 0){
cout<<"\nBytes read: "<<n<<endl;
write(connectFD, buf, n);
}
cout<<"\nTest after read\n";
exit(0);
}

这个输出是:

Bytes read: 4096

Bytes read: 4096

Bytes read: 4096

Bytes read: 4046

Test after read

与客户端中的代码相比,这里有什么不同?为什么读取调用不像在客户端那样阻塞?

最佳答案

The read call seem to block after it's done reading from the socket and never leave the loop. How can I fix this?

简答,收到所有数据后不要调用read

编写代码来检测您何时收到了当时想要收到的所有数据,如果是,则退出循环。您必须实际实现某种协议(protocol)。

s+=readBuf;

这不可能是对的。它如何知道要向 s 添加多少字节的数据?

关于c++ - 读取和写入套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13542780/

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