Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, This is my first time trying to write an actual program in C++

my program communicates using sockets and I faced some problems, I tried to implement file transfer functionality. when I used to code similar programs in python I would first encode the data of the file in base64 and decode it on the other side, so I tried doing that here.

but for some reason the base64 string does get sent or received as the full string. I only get the first part of the string but the rest is lost.

What I have tried:

I tried writing my own send and receive functions because I thought it might be a size problem, but that resulted in the same behavior.

the send function (called "sendAll") takes a vector that is a string split to chunks by another function I found online, and then sends one after another to the socket, and then sends a special string "<end_of_socket_data>".

the receive function (called "recvAll") receives the data one after another and puts them all together and then gives them back to me after it received the special string "<end_of_socket_data>".

I will post the functions in case these were of any interest.

sendAll:
int sendAll(int socket, vector<string> ls, int flag)
{
    int total_size;
    int size_now;
    string str;

    for(int i = 0; i < ls.size(); i++) {
        str = ls.at(i);
        size_now = send(socket, str.c_str(), sizeof(str.c_str()), flag);

        MessageBox(NULL, str.c_str(), "Data", MB_OK);

        total_size += size_now;

    }
    char end_message[100] = "<END_OF_SOCKET_DATA>";

    send(socket, end_message, sizeof(end_message), 0);

    return total_size;
}

recvAll:
int recvAll(int socket, string& full_str)
{
	full_str = "";

	int total_size = 0;
	int size_now = 0;
	char chunk[CHUNK_SIZE];

	while(1) {

		bzero(chunk, sizeof(chunk));

		size_now = recv(socket, chunk, sizeof(chunk), 0);

		if(strcmp(chunk, "<END_OF_SOCKET_DATA>") == 0)
		{
			break;
		}
		else
		{		
			full_str += chunk;

			total_size += size_now;
		}

	}
	return total_size;

}
Posted
Updated 1-Mar-21 4:53am

1 solution

Compile and run the following program
C++
#include <iostream>
#include <cstring>

using namespace std;


int main()
{
  string s = "foo bar 01234567890";

  cout << "sizeof (s.c_str() ) = " << sizeof( s.c_str()) << endl;
  cout << "strlen( s.c_str() ) = " << strlen( s.c_str()) << endl;
  cout << "s.lenght() = " << s.length() << endl;
}


(Hint: The sizeof operator is not what you need, on a character pointer).
 
Share this answer
 
Comments
Member 14915174 1-Mar-21 11:03am    
Thanks, didn't know that.
CPallini 1-Mar-21 11:08am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900