I have a client/server socket program that writes packets of file data in a char[2048], I've made 100% sure to null terminate all of the arrays before sending over the socket.
However on the server side I can't get the ofstream to output to the file if I do not have an endl, however this endl inserts itself at the end of the packets and makes the file have newlines in them where I don't want them to.
Here is what should be the relevant code
client
void Copy(char *filename1,string filename2,int Sockfd) {
const int BUFSIZE=2048;
char buffer[BUFSIZE];
ifstream fin;
long filelen, bytesRemaining, bytes;
// Open the file to be transferred, check it exists.
fin.open( filename1);
if (!fin.good()) {
cerr << "Problems opening \"" << filename1 << "\" (" << errno << "): " << strerror(errno) << endl;
exit(1);
}
// Determine the file's length.
fin.seekg(0,ios::end);
if(fin.fail()) cerr<<"seekg() fail!\n";
filelen = fin.tellg();
if(fin.fail()) cerr<<"tellg() fail!\n";
fin.seekg(0, ios::beg);
if(fin.fail()) cerr<<"seekg() fail!\n";
// Copy the file data.
bytesRemaining = filelen;
while (bytesRemaining > 0)
{
bytes = bytesRemaining > BUFSIZE ? BUFSIZE : bytesRemaining;
buffer[bytes] = '\0';
fin.read(buffer,bytes);
if(fin.fail())
{
cerr<<"read() errror\n";
exit(1);
}
send(Sockfd,buffer,sizeof buffer,0);
recv(Sockfd,buffer,strlen(buffer),0);
bytesRemaining -= bytes;
}
fin.close();
}
And Server
int retval;
char EchoBuffer[RCVBUFSIZE]; // Buffer for echo string
int RecvMsgSize; // Size of received message
std::ofstream fout;
fout.open("test.txt",std::ios::ate);
// Send received string and receive again until end of transmission
while(RecvMsgSize > 0)
{ // zero indicates end of transmission
// Echo message back to client
if(send(ClntSocket, EchoBuffer, RecvMsgSize, 0) != RecvMsgSize){
perror("send() failed"); exit(1);
}
// See if there is more data to receive
if((RecvMsgSize = recv(ClntSocket, EchoBuffer, RCVBUFSIZE-1, 0)) < 0){
perror("recv() failed"); exit(1);
}
EchoBuffer[RecvMsgSize] = '\0';
fout << EchoBuffer << endl; //If I don't have this endl, it won't work at all
}
fout.close();
close(ClntSocket); // Close client socket
}
You should write fout.flush();
after fout << EchoBuffer;
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.