I'm building the communication module of an application on c++, I'm using windows socket to make the connection and the send() function to send files. When I try to send an image, it comes broken in the server client, but when I send a Text File, it works normally.
My application is divided into Client and Server. My Client connects to the Server and stores a png file into a string variable (data). Out of 512 out of 512 bites, the program stores the array that contains the image into "data", and send it via socket::
//Stores the binary
int imgBinaryExtractor(){
int i = 0;
std::ifstream file1;
char ch; //Used to storde the image characters into img_binary
const char* sfile = "original.png";
file1.open(sfile, std::ios::binary);
while (file1.get(ch)) {
img_binary[i] = ch; //Put the png data into the array
file_size++; //Stores the size of the image
i++; //Just a controller
//std::cout << "\nCaractere atual no char: " << ch;
//std::cout << "\nCaractere atual no aray: " << img_binary[i];
}
file1.close();
std::cout << "file_size: " << file_size << std::endl;
int a = 512;
while(controle_file_size <= a){
// data = data+img_binary[a];
// if(img_binary[a] != "\n"){
data = data + img_binary[controle_file_size];
controle_file_size++;
//}
}
a = controle_file_size + 512;
return 0;
}
//Sends the image:
int data_send(std::string data){
std::cout << "\nData send has been called";
sent_message = "\nSending Image";
send(client.socket, sent_message, strlen(sent_message), 0);
sent_message = data.c_str();
send(client.socket, sent_message, strlen(sent_message), 0);
sent_message = "\nThe image has been send";
send(client.socket, sent_message, strlen(sent_message), 0);
}
And to be sure that all the file has been sent, I created this logic on Int Main:
int main(){
std::thread worker1(conectar, "127.0.0.1", "8080"); //COnnection thread
std::cout << "\nPress any button to send the image";
system("pause");
std::thread worker2(data_send, data); //Data send
while(controle_file_size < file_size){
imgBinaryExtractor();
std::cout << data;
worker2.join(); //
}
worker1.join();
// worker2.join();
std::cout << "\nThe image has been sent" << std::endl;
}
In the server code:
This recives the 512 bites from the client and stores it into the "binario" variable:
while (1)
{
//memset(tempmsg, 0, DEFAULT_BUFLEN);
if (new_client.socket != 0)
{
int iResult = recv(new_client.socket, tempmsg, DEFAULT_BUFLEN, 0);
std::cout << "\nSize of buffer is: " << strlen(tempmsg);
if (iResult != SOCKET_ERROR)
{
if (strcmp("", tempmsg))
//msg = "PC filho #" + std::to_string(new_client.id) + ": " + tempmsg;
std::cout << tempmsg;
binario = tempmsg;
binaryStorer(binario);
Later it calls this funcion to store the binary into a png file.
int binaryStorer(std::string binario){
int i = 0;
std::ofstream file2;
const char* tfile = "passed-image.png";
file2.open(tfile, std::ios::binary);
file2 << binario;
file2.close();
return 0;
}