Reg tcpserver in erlang

Nrapesh Khamesra nrapesh09@REDACTED
Thu Dec 9 09:19:00 CET 2010


    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.


More information about the erlang-questions mailing list