对于TCP协议上,如果直接发送一个文件给客户端,如果关闭方式没有关闭好,那么会导致文件数据发送不完全。看下面一段程序。
#include "Acceptor.h"
#include "InetAddress.h"
#include "TcpStream.h"
#include <thread>
#include <unistd.h>
void sender(const char* filename, TcpStreamPtr stream)
{
FILE* fp = fopen(filename, "rb");
if (!fp)
return;
printf("Sleeping 10 seconds.\n");
sleep(10);
printf("Start sending file %s\n", filename);
char buf[8192];
size_t nr = 0;
while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0)
{
stream->sendAll(buf, nr);
}
fclose(fp);
printf("Finish sending file %s\n", filename);
// Safe close connection
printf("Shutdown write and read until EOF\n");
stream->shutdownWrite();
while ( (nr = stream->receiveSome(buf, sizeof buf)) > 0)
{
// do nothing
}
printf("All done.\n");
// TcpS