[erlang-questions] Simple TCP Server

Joe Armstrong erlang@REDACTED
Wed Dec 18 08:07:37 CET 2013


Try something like this

-module(mock_tcp).
-export([start/1]).

%% start with
%%   erl -s mock_tcp start <port> <file>
%% for example
%%   erl -s mock_tcp start 1234 foo.txt

start([APort, AFilename]) ->
    Port = list_to_integer(atom_to_list(APort)),
    Filename = atom_to_list(AFilename),
    {ok, Listen} = gen_tcp:listen(Port, [binary]),
    spawn(fun() -> connect(Listen, Filename) end),
    io:format("Server available on port ~p. Reading from file ~p.",
[Port, Filename]).

I'd recommend ~p in the format rather than ~w (~p is "pretty-print"),
~w might not print
what you had expected)

Cheers

/Joe


On Tue, Dec 17, 2013 at 10:54 PM, Fred Youhanaie <fly@REDACTED> wrote:
>
> To add to the other suggestions:
>
> 0. Does it work if you run it from the erlang shell?
>
> 1. If you're starting it with "erl -s ..." then the port number will be
> passed as atom, rather than integer! So you'll need to convert to integer.
>
> 2. In the get_date() you probably meant to use file:read_line/1, rather than
> io:get_line/1.
>
> Cheers
> f.
>
>
>
> On 17/12/13 18:53, Ari King wrote:
>>
>> Hi,
>>
>> The code below results in "init terminating in do_boot." Seemingly the
>> problem is on line 5, does anyone see what is wrong with it? Additionally,
>> I'm trying to pass the port in as a command line argument, but for some
>> reason it doesn't work and I need to hardcode it.
>>
>> -module(mock_tcp).
>> -export([start/1]).
>>
>> start([Port, Filename]) ->
>>    {ok, Listen} = gen_tcp:listen(Port, [binary]),
>>    spawn(fun() -> connect(Listen, Filename) end),
>>    io:format("Server available on port ~w. Reading from file ~w.", [Port,
>> Filename]).
>>
>> connect(Listen, Filename) ->
>>    {ok, Socket} = gen_tcp:accept(Listen),
>>    spawn(fun() -> connect(Listen, Filename) end),
>>    {ok, Device} = file:open(Filename, read),
>>    get_data(Device, Socket).
>>
>> get_data(Device, Socket) ->
>>    case io:get_line(Device) of
>>      {ok, Data} ->
>>        gen_tcp:send(Socket, Data),
>>        get_data(Device, Socket);
>>      eof ->
>>        file:close(Device),
>>        gen_tcp:close(Socket)
>>    end.
>>
>> Thanks.
>>
>> -Ari
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list