gpt4 book ai didi

c - 如何将任意大文件读取到 C 中的 TCP 套接字?

转载 作者:可可西里 更新时间:2023-11-01 02:52:49 24 4
gpt4 key购买 nike

我正在学习套接字编程,我正在尝试编写一个回显客户端,它从标准输入读取并写入套接字,然后从套接字读取服务器响应到标准输出。问题是我不知道 stdin 会有多长时间或者服务器的响应会有多长时间。我尝试使用的代码如下(创建套接字和连接到服务器被省略):

length = BUF_SIZE;
while (length == BUF_SIZE) { // length will equal BUF_SIZE if buf is full, when length < BUF_SIZE we have reached an EOF
// Reads from STDIN to buf
if ((length = read(STDIN_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error in reading from STDIN");
return 4;
}
// Writes from buf to the socket
if ((write(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to socket");
return 5;
}
}

if ((status = shutdown(sock, 1)) < 0){ // Shuts down socket from doing more receives
fprintf(stderr, "Error shutting down socket for writing");
return 6;
}

length = BUF_SIZE;
while (length == BUF_SIZE){
// Read from socket to buf
if ((length = read(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error reading from socket");
return 7;
}
// Write from buf to STDOUT
if ((write(STDOUT_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to STDOUT");
return 8;
}
}

close(sock);
exit(0);

BUF_SIZE 定义为 100。当我运行我的程序时,程序通常会连接到服务器并发送正确的消息,但它写入 stdout 的内容要么什么也没有,要么是乱码。

我做错了什么?

最佳答案

您的 while 循环只会在第一次运行时起作用。 read()/write() 只会返回它们实际读/写的数量,这很可能不等于 BUF_SIZE。假设您从套接字读取了 10 个字节,然后将 100 个字节写入标准输出 - 最后 90 个字节将成为垃圾。

按照这些思路做的事情会让您更接近您想要的。

while (1)
{
if ((length = read(STDIN_FILENO, buf, BUF_SIZE)) < 0)
{
fprintf(stderr, "Error in reading from STDIN");
return 4;
}

if ((write(sock, buf, length)) < 0)
{
fprintf(stderr, "Error writing to socket");
return 5;
}

if ((length = read(sock, buf, BUF_SIZE)) < 0)
{
fprintf(stderr, "Error reading from socket");
return 7;
}

if ((write(STDOUT_FILENO, buf, length)) < 0)
{
fprintf(stderr, "Error writing to STDOUT");
return 8;
}
}

关于c - 如何将任意大文件读取到 C 中的 TCP 套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9171321/

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