zoukankan      html  css  js  c++  java
  • [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.
  • 相关阅读:
    source : not found 原因及解决办法
    hdfs 数据坏块导致datanode不能正常上报数据块
    hadoop 基准测试
    Linux yum 安装mysql的时候指定安装版本
    如何从头构建一个只有bash的镜像
    创建自己的基础镜像
    go学习(2)变量
    Go学习(1)go安装
    spark on yarn 错误
    mysqld: File './mysql-bin.index' not found (Errcode: 13
  • 原文地址:https://www.cnblogs.com/bluefrog/p/2679040.html
Copyright © 2011-2022 走看看