我制作这段代码来解决这个问题。
我发送 30 个字节作为文件名。
如果文件名<30,我使用白色字符填充。
当连接被接受时,我调用函数 file_name_receiver(Socket),它接收文件名:
file_name_receiver(Socket)->
{ok,FilenameBinaryPadding}=gen_tcp:recv(Socket,30),
FilenamePadding=erlang:binary_to_list(FilenameBinaryPadding),
Filename = string:strip(FilenamePadding,both,$ ),
file_receiver_loop(Socket,Filename,[]).
此函数提供二进制数据文件:
file_receiver_loop(Socket,Filename,Bs)->
io:format("~nRicezione file in corso~n"),
case gen_tcp:recv(Socket, 0) of
{ok, B} ->
file_receiver_loop(Socket, Filename,[Bs, B]);
{error, closed} ->
save_file(Filename,Bs)
end.
最后,这个函数保存文件。
%%salva il file
save_file(Filename,Bs) ->
io:format("~nFilename: ~p",[Filename]),
{ok, Fd} = file:open("../script/"++Filename, write),
file:write(Fd, Bs),
file:close(Fd).
发件人使用一个简单的功能:
%%Permette l'invio di un file specificando host,filename e path assoluto
send_file(Host,Filename,FilePath,Port)->
{ok, Socket} = gen_tcp:connect(list_to_atom(Hostname), Port, TCP_OPTIONS_CLIENT),
FilenamePadding = string:left(Filename, 30, $ ), %%Padding with white space
gen_tcp:send(Socket,FilenamePadding),
Ret=file:sendfile(FilePath, Socket),
ok = gen_tcp:close(Socket).