I am trying to send a Base64 encoded image from TCP client using GO and TCP server in C++.
Here is the code snippet for C++ Receiver
std::string recieve(int bufferSize=1024,const char *eom_flag = "<EOF>"){
char buffer[bufferSize];
std::string output;
int iResult;
char *eom;
do{
iResult = recv(client, buffer, sizeof(buffer), 0);
//If End OF MESSAGE flag is found.
eom = strstr(buffer,eom_flag);
//If socket is waiting , do dot append the json, keep on waiting.
if(iResult == 0){
continue;
}
output+=buffer;
//Erase null character, if exist.
output.erase(std::find(output.begin(), output.end(), '\0'), output.end());
//is socket connection is broken or end of message is reached.
}while(iResult > -1 and eom == NULL);
//Trim <EOF>
std::size_t eom_pos = output.rfind(eom_flag);
return output.substr(0,eom_pos);}
Idea is to receive the message until End of Message is found, thereafter continue to listen for another message on the same TCP connection.
Golang TCP client code snippet.
//Making connection
connection, _ := net.Dial("tcp", "localhost"+":"+PortNumber)
if _, err := fmt.Fprintf(connection, B64img+"<EOF>"); err != nil {
log.Println(err)
panic(err)
}
Tried approaches:
- Increasing the buffer size in the C++ receiver.
- Removing the null character from the end of the string in the C++ receiver.
Observations:
Length of string sent by the client is fixed, while the length of the string after receive function is larger and random. Example: Go client string length is 25243. For the same string, length after receive when i run send and receive in the loop is 25243, 26743, 53092, 41389, 42849.
On Saving the received string in a file, I see <0x7f> <0x02> character in the string.
I am using winsock2.h for c++ socket.
recvdoes not necessarily give back as many bytes as will fit in the buffer - the function returns the number of bytes actually returned as its result. You should account for that where you currently dooutput+=buffer;. - 500 - Internal Server Errorchar buffer[bufferSize];-- This is not valid C++. Usestd::vector<char> buffer(bufferSize);- PaulMcKenzierecvcall,if (iResult == 0) { continue; }is wrong. The only time you will get a return value of zero is if/when your peer has disconnected. By usingcontinue, you'll then just repeat therecv, which will simply return 0 again, resulting in an infinite loop. - Gil Hamilton