简体   繁体   English

当使用 send() 通过 TCP 流将文本文件中的数据从客户端发送到服务器时,如何发送所有数据但一次仅发送 4 个字节?

[英]When using send() to send data from a text file from client to server through TCP stream, how do I send all the data but only 4 bytes at a time?

Below is an excerpt from my client.cpp file:以下是我的 client.cpp 文件的摘录:

//Variables previously declared
char buffer[1024];
char sendbuffer[100];
int sockfd, b;

//Opens specified file
FILE *fp = fopen(argv[3], "rb"); 

while( (b = fread(sendbuffer, 1, sizeof(sendbuffer), fp)) > 0 ) 
{
    send(sockfd, sendbuffer, b, 0);
}


I am new to client-server programming, and I'm far from being extremely proficient in C++.我是客户端-服务器编程的新手,而且我远非精通 C++。

When I use the code above, it's successful sending the inf, but it obviously isn't going to send the data 4 bytes at a time.当我使用上面的代码时,它成功发送了 inf,但显然不会一次发送 4 个字节的数据。

If I modified the line containing send() as shown below without making other necessary changes, I'm certain that it would be incorrect.如果我修改了包含 send() 的行,如下所示,而不进行其他必要的更改,我确信它是不正确的。

send(sockfd, sendbuffer, 4, 0);

It's also a pain to debug because when I make a change to the code, I have to continuously simulate a client-server interaction, which takes time to set up.调试也很痛苦,因为当我对代码进行更改时,我必须不断模拟客户端-服务器交互,这需要时间来设置。

What would be the most efficient way to send this text file data 4 bytes at a time?一次发送 4 个字节的文本文件数据的最有效方法是什么?

Also, can anyone suggest a tool or method for quickly debugging client-server programs?另外,任何人都可以建议一种快速调试客户端 - 服务器程序的工具或方法吗?

Let me know if more information is needed.如果需要更多信息,请告诉我。 Thanks谢谢

Well, you can try to send 4 bytes at a time and it will probably work but you have no control of how many bytes a stream socket will actually send.好吧,您可以尝试一次发送 4 个字节,它可能会起作用,但您无法控制流套接字实际发送的字节数。 You have to check the return value.您必须检查返回值。 I do not think you need to debug the program at all.我认为您根本不需要调试程序。 Logging is better because it does not introduce time delays like debugging does, and time is money in the networking world.日志记录更好,因为它不会像调试那样引入时间延迟,并且在网络世界中时间就是金钱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM