> Erlang中文手册 > sendfile/2 通过套接字端口 Socket 发送文件数据

file:sendfile/2

通过套接字端口 Socket 发送文件数据

用法:

sendfile(Filename, Socket) -> {ok, BytesSent} | {error, Reason}

内部实现:

%% sendfile/2
-spec sendfile(Filename, Socket) ->
   {'ok', non_neg_integer()} | {'error', inet:posix() | 
				closed | badarg | not_owner}
      when Filename :: name_all(),
	   Socket :: inet:socket().
sendfile(Filename, Sock)  ->
    case file:open(Filename, [read, raw, binary]) of
	{error, Reason} ->
	    {error, Reason};
	{ok, Fd} ->
	    Res = sendfile(Fd, Sock, 0, 0, []),
	    file:close(Fd),
	    Res
    end.

通过套接字端口 Socket 发送文件 Filename 的数据。如果发送成功,则返回 {ok, BytesSent},否则,返回 {error, Reason}

{ok, Socket} = gen_tcp:connect(?HOST, ?PORT, [binary, {packet, 0}]),
file:sendfile("/app/rebar.config", Socket).