1

我很高兴发送一个文件,它是文件名。服务器选项:

-define(TCP_OPTIONS_SERVER, [binary, {packet, 0}, {active, false}]).

那是接收器循环:

file_receiver_loop(Socket,Bs)->
case gen_tcp:recv(Socket, 0) of
    {ok, B} ->
        file_receiver_loop(Socket, [Bs, B]);
    {error, closed} ->
        io:format("~nReceived!~n ~p",[Bs]),
        save_file(Bs)
end.

我发送文件:

file:sendfile(FilePath, Socket),

当我发送文件和文件名时

gen_tcp:send(Socket,Filename),
file:sendfile(FilePath, Socket),

二进制数据具有可变结构。

谢谢大家!

4

2 回答 2

0

我制作这段代码来解决这个问题。
我发送 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).
于 2012-12-11T14:49:58.887 回答
0

我制作了两个函数,您可以在其中发送带有消息传递的二进制文件。

%Zip a file or a folder
send_zip(Pid, FolderName) ->
    %Name of you zip file
    FolderNameZip= FolderName++".zip",   
    %Zip the folder/file from the computer and name the zip file by FornderNameZip                    
    {ok, ZipFile} = zip:create(FolderNameZip, [FolderName]),
    %Put the Zipfile in a variable 
    {ok, ZipHandle} = file:read_file(ZipFile),
    %Send the zipfile to the other PID, sends the zipfile and his name to name it the same way.
    Pid ! {finish, ZipHandle, FolderNameZip}.


%save and unzip the in the computer 
register_zip_bash(Dir, ZipHandle, FolderNameZip) -> 
    file:write_file(FolderNameZip, ZipHandle),
    Cmd2 = io_lib:format("unzip -o -j ~p -d ~p/",[FolderNameZip, Dir]),
    _=os:cmd(Cmd2).

FoldeName 可以是您计算机中文件或文件夹的名称。Pid 是您要发送消息的人。

当您收到 ZipHandle 和 FolderNameZip 时,使用 register_zip_bash(...) 函数将数据保存在您的计算机中。Dir 是您要保存数据的目录。ZipHandle 是您从 PID 函数接收的二进制文件。FolderNameZip 是 ZipHandle 将在计算机中保存的位置的名称。

如您所见, send_zip(...) 使用 erlang 函数,而 register_zip_bash(...) 使用 bash 命令。您不必压缩文件来发送数据。不要犹豫,更改代码以使其适合您。

希望这会有所帮助,干杯。

于 2019-12-16T14:48:30.553 回答