eof error reading pieces of text file and writing to boost.asio socket
I'm trying to read a file 1kB at a time and write each piece of data to a socket using boost.asio. The problem is that when I need to read the last piece of data from the text file and put it in the buffer, it doesnt seem to work.
I need a way to print the last part of the buffer without printing the whole buffer (because it contains leftovers from the previous iteration of the loop)
int portNumber = 2002;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), portNumber));
tcp::socket socket开发者_JAVA百科(io_service);
acceptor.accept(socket);
boost::system::error_code ignored_error;
int length;
char* buffer = new char[1025];//1024 bytes for data, 1 byte for seqNum
//get file stream and open local file.
ifstream stream;
stream.open("SampleFile.txt", ios::binary);
stream.seekg(0, ios::end);
length = stream.tellg();
stream.seekg(0, ios::beg);
while (!stream.eof())
{
//char sequenceNumber = '0';
stream.read(buffer, 1024);
buffer[1024] = sequenceNumber;//set last pos to seq num
boost::asio::write(socket, boost::asio::buffer(buffer),
boost::asio::transfer_all(), ignored_error);
.
. //do other things
.
}
This will eventually write everything to the socket (assuming the client end is cooperating) except that a portion of the end of the file will get written twice.
1) You aren't correctly computing the size of the final buffer.
2) You aren't correctly testing the stream for error or eof conditions.
Try this:
while (stream)
{
stream.read(buffer, 1024);
buffer[1024] = sequenceNumber++;//set last pos to seq num
boost::asio::write(socket, boost::asio::buffer(buffer, stream.gcount()),
boost::asio::transfer_all(), ignored_error);
...
}
精彩评论