Search code examples
c++c++11operating-systemclient-serverposix

In a client-server program, is it possible for the server to write multiple lines to the client, using the write() function?


For example, if the client asks the server for the biggest and the smallest size of a particular object, the server would need to reply to the client's request with both variables. Is it possible to send two strings from the server for the client to output?


Solution

  • Yes, this is possible. You can use write() to write a number of bytes. You just need to collect the data in a contiguous area and then handle a pointer to that area to write, of course with the number of data to write.

    You can also call write in a loop to write different areas.

    A contiguous area can also have the size 1. Meaning, you can write byte by byte. In a loop. Or as single statements.

    To build your data area, you can use different STL containers, like std::string or std::vector. To access the data, you can use member functions (like c_str() or data();

    If you want to have complete freedom, you may want to use an std::ostringstream. Here you can insert data like in std::cout and then send the result with write to anywhere.

    I prepared an example for you.

    Please note. As file descriptor I am using 1. This is equivalent to std::cout. So you will see the result of the program in the console.

    #include <io.h>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>
    
    
    // File descriptor. For test purposes we will write to the console
    constexpr int testFdforStdOut = 1;
    
    int main()
    {
        // String parts
        std::string part1("Part1\n");
        std::string part2("Part2\n");
        std::string part3("Part3\n");
        // Combine all strings
        std::string allData = part1 + part2 + part3;
        // Write all data
        _write(testFdforStdOut, allData.c_str(), allData.size());
    
        // Vector of strings
        std::vector<std::string> vectorOfStrings{ "\nPart4\n", "Part5\n", "Part6\n", "Part7\n" };
        // Write data in a loop
        for (const std::string&s : vectorOfStrings)
            _write(testFdforStdOut, s.c_str(), s.size());
    
        std::ostringstream oss;
        oss << "\nTest for anything\n" << 2 << '\n' << 3 * 3 << "\nPart8\n";
        _write(testFdforStdOut, oss.str().c_str(), oss.str().size());
    
        return 0;
    }