[erlang-questions] Simple TCP Server

Fred Youhanaie <>
Wed Dec 18 23:48:40 CET 2013


So, 1 down and 2 to go :-)

0. Does it work if you run it from the *erlang* shell?

2. In the get_date() you probably meant to use file:read_line/1, rather than io:get_line/1.

The error message is saying that by the time gen_tcp:accept/1 is called, the socket has been closed. Try item #0 above.

BTW, since you're learning, I have resisted giving you the complete solution so that you enjoy the discovery first hand :)

Cheers
f.


On 18/12/13 17:40, Ari King wrote:
> I incorporated the suggestions and it solved the issue of setting up a
> socket to listen on a specified port(line 5). However, a new issue has
> risen while attempting to accept a connection on the listening socket. The
> error message follows:
>
> =ERROR REPORT==== 18-Dec-2013::17:32:47 ===
> Error in process <0.32.0> with exit value:
> {{badmatch,{error,closed}},[{mock_tcp,connect,2,[{file,"mock_tcp.erl"},{line,12}]}]}
>
> I'm starting the server via erl -s mock_tcp start 8080 <path_to_file>
>
> -module(mock_tcp).
> -export([start/1]).
>
> start([AtomPort, AtomFilename]) ->
>    Port = list_to_integer(atom_to_list(AtomPort)),
>    Filename = atom_to_list(AtomFilename),
>    {ok, Listen} = gen_tcp:listen(Port, [binary, {reuseaddr, true}]),
>    spawn(fun() -> connect(Listen, Filename) end),
>    io:format("Server available on port ~p. Reading from file ~p.", [Port,
> Filename]).
>
> connect(Listen, Filename) ->
>    % Following line causes the error
>    {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



More information about the erlang-questions mailing list