I'm trying to send a file through socket.
When I set len of send() to be more than 1024, there're chances of receiving wrong data from send().
If I set len to be 1024, it always works fine.
Is it because the MTU limit of 1500 bytes? If so, why The maximum send buffer size is 1,048,576 bytes?
Core parts of the code:
\\server.cpp
fstream in(cmds[1], ios::in | ios::binary);
size_t chunk, rest;
in.seekg(0, ios::end);
chunk = in.tellg() / MAXTEXT;
rest = in.tellg() % MAXTEXT;
in.seekg(0, ios::beg);
connfd.send(&chunk, sizeof(size_t));
connfd.send(&rest, sizeof(size_t));
perror("Error: ");
for (size_t i = 0; i < chunk; ++i) {
in.read(buf, MAXTEXT);
connfd.send(buf, MAXTEXT);
}
in.read(buf, rest);
connfd.send(buf, rest);
in.close();
cout << "File upload done" << endl;
\\client.cpp
fstream out(cmds[2], ios::out | ios::binary);
size_t chunk, rest;
connfd.recv(&chunk, sizeof(size_t));
connfd.recv(&rest, sizeof(size_t));
perror("Error: ");
auto startTime = chrono::high_resolution_clock::now();
for (size_t i = 0; i < chunk; ++i) {
connfd.recv(buf, MAXTEXT);
out.write(buf, MAXTEXT);
// show_process_bar((double)(i+1)/(double)chunk);
}
connfd.recv(buf, rest);
out.write(buf, rest);
auto endTime = chrono::high_resolution_clock::now();
auto totalTime = chrono::duration_cast<chrono::milliseconds>(endTime - startTime).count();
out.close();
cout << "File download done, Total time: "
<< totalTime
<< "ms, Average speed: "
<< chunk * MAXTEXT / 1024 / 1024 * 1000 / totalTime
<< " MiB/s" << endl;
when type "get /mnt/c/Users/yieatn/Documents/test.pdf /home/yieatn/test.pdf"
It tends to work fine in the first time, but then i found chunk and rest are messed up
I'm guessing some data weren't wroten into buf, which causes unexpected data wroted into chunk and rest
version:
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2
the complete code can be found here code