The implementation of publishTime is straightforward.
- The implementation itself, however, isn't the focus. Strictly speaking, it's generating dynamic content—uninteresting, but dynamic, nonetheless—and publishing it back to the client over the socket descriptor.
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\n", ptm);
size_t numBytesWritten = 0, numBytesToWrite = strlen(timeString);
while (numBytesWritten < numBytesToWrite) {
numBytesWritten += write(clientSocket,
timeString + numBytesWritten,
numBytesToWrite - numBytesWritten);
}
close(clientSocket);
}
- The first five lines here produce the full time string that should be published. Let these five lines represent more generally the server-side computation needed for the service to produce output. Here's is the current time, but it could have been a static HTML page, a Google search result, an RSS XML document, an image, or a Netflix video.
- The remaining lines publish the time string—we'll call it the payload—to the client socker using the raw, low-level I/O we've seen before.