Problem sending 2 files to the client using Boost.Asio, Error: read: End of file [asio.misc:2]
I want to send two files to the client, the first file is img.jpg and the second file is message.txt
The first file img.jpg is received correctly, but the file message.txt is received with size zero
client output is:
img.jpg: 49152
message.txt: 4096
read: End of file [asio.misc:2]
here are my client and server codes:
server.cpp:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <boost/asio.hpp>
int main(int argc, char* argv[])
{
try
{
boost::asio::io_context io;
std::cout << "Server Start\n";
boost::asio::ip::tcp::acceptor acc(io,
boost::asio::ip::tcp::endpoint(
boost::asio::ip::tcp::v4(), 6666));
for (;;) {
boost::asio::ip::tcp::socket sock(io);
acc.accept(sock);
std::vector<std::string> names{ "img.jpg" , "message.txt"};
std::vector<int> sizes{ 49152 , 4096 };
for (int i = 0; i < 2; ++i) {
//Send Header
boost::asio::streambuf reply;
std::ostream header(&reply);
header << names[i] << " ";
header << std::to_string(sizes[i]) << " ";
header << "\r\n";
boost::asio::write(sock, reply);
//Send Bytes
std::ifstream input(names[i], std::ifstream::binary);
std::vector<char> vec(sizes[i]);
input.read(&vec[i], sizes[i]);
boost::asio::write(sock, boost::asio::buffer(vec, sizes[i]));
}
sock.close();
}
acc.close();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
client.cpp:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <boost/asio.hpp>
int main(int argc, char* argv[])
{
try
{
boost::asio::io_context io;
boost::asio::ip::tcp::resolver resolv(io);
boost::asio::ip::tcp::resolver::query q("127.0.0.1", "6666");
boost::asio::ip::tcp::resolver::iterator ep = resolv.resolve(q);
boost::asio::ip::tcp::socket sock(io);
boost::asio::connect(sock, ep);
//Get Files
for (int i = 0; i < 2; ++i) {
//Read Header
boost::asio::streambuf reply;
boost::asio::read_until(sock, reply, "\r\n");
std::istream header(&reply);
std::string fileName;
int fileSize;
header >> fileName;
header >> fileSize;
std::cout << fileName << ": " << fileSize << '\n';
//Read File Data
std::ofstream output(fileName, std::ofstream::binary | std::ofstream::app);
std::vector<char> vec(fileSize);
boost::asio::read(sock, boost::asio::buffer(vec, vec.size()));
output.write(&vec[0], vec.size());
output.close();
}
sock.close();
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
Read more here: Source link
