I'm trying to make a program which sends to the server a .txt file, modifies it's content and then sends the modified content back to the client in C++. I have managed to make the tcp/ip communication to work fine for simple string text messages, but when I try to send the content of a .txt file, it fails to do so.
Here's a snippet of my code: (
Client:
fstream file;
string fileName = "Test.txt";
string textToSend;
int sendResult;
file.open(fileName);
while (!file.eof())
{
getline(file, textToSend);
sendResult = send(sock, textToSend.c_str(), textToSend.size() + 1, 0);
}
string end_msg = "end";
sendResult = send(sock, end_msg.c_str(), end_msg.size() + 1 , 0);
file.close();
if (sendResult != SOCKET_ERROR)
{
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
cout << "Server> " << string(buf, 0, bytesReceived) << endl;
}
else
{
cout << "Error on client - bytesReceived" << endl;
}
}
// Gracefully close down everything
closesocket(sock);
WSACleanup();
}
Server:
// While loop: accept and echo message back to client
char buf[4096];
while (true)
{
ZeroMemory(buf, 4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Quitting!" << endl;
break;
}
else
{
if (bytesReceived == 0)
{
cout << "Client disconnected!" << endl;
break;
}
}
buf[bytesReceived] = '\0';
while (buf != "end")
{
cout << buf << endl;
bytesReceived = recv(clientSocket, buf, 4096, 0); //Here seems to be the problem in debug mode
buf[bytesReceived] = '\0';
}
cout << string(buf, 0, bytesReceived) << endl;
// Echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
}
// Close socket
closesocket(clientSocket);
// Shutdown Winsocket
WSACleanup();
}
Using debug mode, I noticed that in server side
bytesReceived = recv(clientSocket, buf, 4096, 0);
it can't get to the second row of my text file.
P.S. : I'm new to tcp/ip on c++, having basic experience on Java, Any help is great, thanks.