The socket sends a function.
int send (SOCKET s, const char FAR *buf, int len, int flags
);
If the content is dynamically generated, it is generally the transfer of the content directly to the BUF in the Send function transmission, there is no room for optimization.
The file transfer must first read the content to buf, so at least two times the kernel call, if the file is large, you may use a circular call, such as:
while (size = = per_size)
{
size = read (FD, buf, per_size);
if (size >0)
{
Send (sock, buf, size, 0);
}
}
The number of system calls will be file size/per read size *2, we know that system calls require kernel State and user state switching, as well as system memory and user internal copy, compared to waste valuable CPU time.
Static file transmission of a large number of existence, such as HTML,CSS,JS, transmission efficiency is the server around the problem, it does require specialized optimization.
Linux has been using Sendfile since 2.1 to specifically address this type of problem.
Let's take a look at the function declaration:
ssize_t sendfile (int out_fd, int in_fd, off_t *offset, size_t count);
The parameters are already obvious and will not be introduced.
This function only needs user state and kernel state switch once, all operations in the kernel operation, saving a lot of CPU time, there is no user memory and kernel memory switching, that is, the implementation of "0 copies."
Inside the function is actually IN_FD,OUTFD before the pipeline transmission, no longer introduced.
This technology is used in the Web server today, it can be said that the rapid transmission of static files depends on it.
See more highlights of this column: http://www.bianceng.cn/Servers/zs/