This function is intended to allow the encapsulation of arbitrary non-blocking
system calls as asynchronous operations, in a way that is transparent
to the user of the socket object. The following example illustrates how
Linux's sendfile system
call might be encapsulated:

template<typenameHandler>structsendfile_op{tcp::socket&sock_;intfd_;Handlerhandler_;off_toffset_;std::size_ttotal_bytes_transferred_;// Function call operator meeting WriteHandler requirements.// Used as the handler for the async_write_some operation.voidoperator()(boost::system::error_codeec,std::size_t){// Put the underlying socket into non-blocking mode.if(!ec)if(!sock_.native_non_blocking())sock_.native_non_blocking(true,ec);if(!ec){for(;;){// Try the system call.errno=0;intn=::sendfile(sock_.native_handle(),fd_,&offset_,65536);ec=boost::system::error_code(n<0?errno:0,boost::asio::error::get_system_category());total_bytes_transferred_+=ec?0:n;// Retry operation immediately if interrupted by signal.if(ec==boost::asio::error::interrupted)continue;// Check if we need to run the operation again.if(ec==boost::asio::error::would_block||ec==boost::asio::error::try_again){// We have to wait for the socket to become ready again.sock_.async_write_some(boost::asio::null_buffers(),*this);return;}if(ec||n==0){// An error occurred, or we have reached the end of the file.// Either way we must exit the loop so we can call the handler.break;}// Loop around to try calling sendfile again.}}// Pass result back to user's handler.handler_(ec,total_bytes_transferred_);}};template<typenameHandler>voidasync_sendfile(tcp::socket&sock,intfd,Handlerh){sendfile_op<Handler>op={sock,fd,h,0,0};sock.async_write_some(boost::asio::null_buffers(),op);}