[erlang] gen_tcp传输文件原型
有相关的代码需要使用gen_tcp传输文件 把写的原型发出来
1 -module(tcp). 2 -export([client/1,server/1]). 3 4 client(Port) -> 5 Host = "localhost", 6 {ok,Sock} = gen_tcp:connect(Host,Port,[binary,{packet,0}]), 7 ok = gen_tcp:send(Sock,"/tmp/ecstore.tar"), 8 receive_data(Sock,[]). 9 10 receive_data(Socket,SoFar) -> 11 receive 12 {tcp,Socket,Bin} -> 13 receive_data(Socket,[Bin|SoFar]); 14 {tcp_closed,Socket} -> 15 file:write_file("/tmp/test1.tar",list_to_binary(lists:reverse(SoFar))) 16 end. 17 18 server(Port) -> 19 case gen_tcp:listen(Port,[binary,{packet,0}, %% 每个应用程序消息都从一个4字节长的头部开始 20 {reuseaddr,true}, %% 21 {active,true}]) of 22 {ok,Listen} -> 23 spawn(fun()-> connect(Listen) end); 24 {error,Why} -> 25 io:format("~p~n",[Why]) 26 end. 27 28 connect(Listen) -> 29 case gen_tcp:accept(Listen) of %% 等待暂停并等待一个连接 30 {ok,Socket} -> 31 spawn(fun() -> connect(Listen) end), 32 loop(Socket); 33 {error,Why} -> 34 io:format("~p~n",[Why]) 35 end. 36 37 loop(Socket) -> 38 receive 39 {tcp,Socket,Bin} -> 40 Str = binary_to_list(Bin), 41 %%io:format("Server received = ~p~n",[Str]), 42 T = case file:read_file(Str) of 43 {ok,Bin1} -> 44 binary_to_list(Bin1); 45 {error,Reason} -> 46 io_lib:format("~p~n",[Reason]) 47 end, 48 gen_tcp:send(Socket,[T]), 49 gen_tcp:close(Socket); 50 {tcp_closed,Socket} -> 51 io:format("Server socket closed~n") 52 end.
think in coding