1

I want send binary data with function send()

functions:

void ssend(const char* data){
    send(socket_fd, data, strlen(data), 0);
}

bool readFile(const char* path){
    std::ifstream ifile(path);
    if(ifile){
        if(!ifile.is_open()){
            ErrorPage("403");
            return true;
        }
        std::string sLine;

        std::string Header = "HTTP/1.1 200 OK\nConnection: Keep-Alive\nKeep-Alive: timeout=5, max=100\nServer: BrcontainerSimpleServer/0.0.1 (Win32) (Whitout Compiler code)\n\n";
        ssend(Header.c_str());

        while(!ifile.eof()){
            getline(ifile, sLine);
            cout << "String: " << sLine << endl;
            cout << "const char*: " << sLine.c_str() << endl;

            ssend(sLine.c_str());
        }
        return true;
    }
    return false;
}

Test:

...
while (1) {
    socket_fd = accept(listen_fd, (struct sockaddr *)&client_addr,&client_addr_length);
    readFile( httpPath );
    recv(socket_fd, request, 32768, 0);
    closesocket(socket_fd);
}
...

When converting to binary string with .c_str(), data disappear. How to solve this problem?

how to send binary data with the function send()?

2 Answers 2

3

In C and C++, strings are terminated with a character with the value of zero ('\0'). So when you say "binary string", you are mixing things that don't go together since binary data is not the same as a string.

Instead of a string, use a BYTE array and pass the length as an additional argument so you know how many bytes to send.

Your use of strlen() will stop counting as soon as it encounters the string terminator.

Sign up to request clarification or add additional context in comments.

4 Comments

std::string can hold binary data so if the OP doesn't convert to a C string he can make that work... (or vector<char>)
Yes, I didn't mean to suggest that it couldn't be made to work but I don't consider it ideal. Aside from the null-terminator issue, there is also the issue of Unicode. So, I don't know what his send() method does, but I kind of think it should send bytes.
I think his send() is sockets API.
Thanks, Jonathan, I used <vector>, +1 for you
1

You could:

void ssend(const std::string& data)
{
  send(socket_fd, data.data(), data.length(), 0);
}

or:

ssend(const std::vector<char>& data)
{
  send(socket_fd, &data[0], data.size(), 0);
}

If you are reading binary data from the file you will need to deal with that as well (e.g. open the file with ios::binary, use read() rather than getline()). You probably want to use some sort of encoding to send binary data out from a web server though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.