[erlang-questions] Reg tcpserver in erlang

Ahmed Omar spawn.think@REDACTED
Thu Dec 9 10:45:52 CET 2010


The first time your code will go well cause the process owning/controlling
the socket is alive and it's the one accepting. But then you spawn a new
process to accept new connections , which will not work cause your main
process (the socket owner) died (because it has no more code to execute) ,
and socket was closed.
 That's when the new spawned process crashes with a bad match cause
gen_tcp:accept will return {error, closed} while you expect {ok, Socket}

On Thu, Dec 9, 2010 at 9:19 AM, Nrapesh Khamesra <nrapesh09@REDACTED>wrote:

>    I implemented a simple parallel tcp server to calculate factorial,the
> code for which is as follows
>
> -module(tcpserver).
> -export([start_server/0]).
>
>
> start_server()->
>        spawn(fun()-> start_server(4001) end).
>
> start_server(Port)->
>
>
> {ok,Listen}=gen_tcp:listen(Port,[binary,{packet,4},{reuseaddr,true},{active,true}]),
>        seq_loop(Listen).
>
>
>
> seq_loop(Listen)->
>        {ok,Socket}=gen_tcp:accept(Listen),
>        spawn(fun()-> seq_loop(Listen) end),
>        loop(Socket),
>        gen_tcp:close(Socket).
>
> loop(Socket)->
>       receive
>                {tcp,Socket,Bin}->
>                        io:format("Server Received Binary ~p ~n",[Bin]),
>                        Number=binary_to_term(Bin),
>                        Factorial=factorial(Number),
>                        gen_tcp:send(Socket,term_to_binary(Factorial)),
>                        loop(Socket);
>                {tcp_closed,Socket}->
>                        io:format("Result Returned to client~n",[])
>        end.
>
> factorial(1)->1;
> factorial(N)->N*factorial(N-1).
>
>
> The client code is as follows
> -module(tcpclient).
> -export([factorial/1]).
>
> factorial(Number)->
>        {ok,Socket}=gen_tcp:connect("localhost",4001,[binary , {packet,4}]),
>        ok=gen_tcp:send(Socket,term_to_binary(Number)),
>        receive
>                {tcp,Socket,Bin}->
>                        io:format("Client recieved Binary ~p ~n",[Bin]),
>                        Val=binary_to_term(Bin),
>                        io:format("Result ~p ~n ",[Val]),
>                        gen_tcp:close(Socket)
>        end.
>
> When i first time I use tcpclient:factorial(N) it gives answer but the
> server side crashes after that giving the error
> 1> tcpserver:start_server().
> <0.34.0>
> Server Received Binary <<131,97,5>>
> Result Returned to client
> 2>
> =ERROR REPORT==== 8-Dec-2010::23:15:01 ===
> Error in process <0.36.0> with exit value:
> {{badmatch,{error,closed}},[{tcpserver,seq_loop,1}]}
>
> Can someone tell me the mistake in my code.
>



-- 
Best Regards,
- Ahmed Omar
http://nl.linkedin.com/in/adiaa
Follow me on twitter
@spawn_think <http://twitter.com/#!/spawn_think>


More information about the erlang-questions mailing list