The while loop around the exposed write calls in the prior example were actually necessary this time.
- The socket descriptor is bound to a network driver that has a limited amount of space.
- In practice, it'd be common to see write's return value be less than the value provided via the third argument.
- Ideally, we'd rely on either C streams (e.g. the FILE *) or C++ streams (e.g. the iostream class hierarchy) to layer over data buffers and manage the while loop around exposed write calls for us.
- Fortunately, we have access to a third-party library that provides this. We're going to operate as if the third-party library is just part of standard C++.
static void publishTime(int clientSocket) {
time_t rawtime;
time(&rawtime);
struct tm *ptm = gmtime(&rawtime);
char timeString[128]; // more than big enough
/* size_t len = */ strftime(timeString, sizeof(timeString), "%c", ptm);
sockbuf sb(clientSocket);
iosockstream ss(&sb);
ss << timeString << endl;
} // the sockbuf closes the socket when it's destroyed
- We rely on the same C library functions to generate the time string.
- This time, however, we insert that string into an iosockstream that itself layers over the client socket.
- Note that the intermediary sockbuf class takes ownership of the socket and closes it when its destructor is called.