WoLFi
WoLFi

Reputation: 35

why is the socket closed Erlang

I'm new in Erlang. My Problem is, that when I start the client for the 1st time everything seems okay, I get the sorted list: <<1,5,72,97,108,108,111>>. But by the 2nd time it won't receive the sorted list, because I think the socket is closed. The output from the Client is "Connection closed".

Here is my code:

Client

-module(client).

-export([client/0]).

client() ->
    case gen_tcp:connect("localhost", 6000, [{mode, binary}]) of
        {ok, Sock} -> 
            Data = [1, "Hallo", 5],
            gen_tcp:send(Sock, Data),
            receive
                {tcp, _, Bin} ->
                    io:fwrite("Received sorted list from server: ~w~n", [Bin]);
                {tcp_closed, _} ->
                    io:fwrite("Connection closed"),
                    gen_tcp:close(Sock)
            end;
        {error,_} -> 
            io:fwrite("Connection error! Quitting...~n")
    end.

Server

-module(server).

-export([server/0]).
-import(mergeSort,[do_recv/1]).

%creates a tcp socket on Port 6000
server() ->
    {ok, Listen} = gen_tcp:listen(6000, [{keepalive, true}, %send keepalive packets
                                         {reuseaddr, true}, %reuse address
                                         {active, once},    %socket is active once
                                         {mode, list}]),    %binary traffic
    spawn(fun() -> parallel_connection(Listen) end).

%server is listening
%accepts the connection
%starts MergeSort
parallel_connection(Listen) ->
    io:fwrite("Listening connections..~n"),
    {ok, Socket} = gen_tcp:accept(Listen),
    io:fwrite("Connection accepted from ~w~n", [Socket]),
    spawn(fun() -> parallel_connection(Listen) end),
    do_recv(Socket).

MergeSort

-module(mergeSort).

-export([do_recv/1]).

merge_sort(List) -> m(List, erlang:system_info(schedulers)).

%break condition
m([L],_) ->
    [L];

%for more than one scheduler
m(L, N) when N > 1  -> 
    {L1,L2} = lists:split(length(L) div 2, L),
    %self () returns Pid, make_ref() returns almost unique reference
    {Parent, Ref} = {self(), make_ref()},
    %starts a new process for each half of the list
    %and sends Message to Parent
    spawn(fun()-> Parent ! {l1, Ref, m(L1, N-2)} end), 
    spawn(fun()-> Parent ! {l2, Ref, m(L2, N-2)} end), 
    {L1R, L2R} = receive_results(Ref, undefined, undefined),
    lists:merge(L1R, L2R);
m(L, _) ->
    {L1,L2} = lists:split(length(L) div 2, L),
    lists:merge(m(L1, 0), m(L2, 0)).

receive_results(Ref, L1, L2) ->
    receive
        {l1, Ref, L1R} when L2 == undefined -> receive_results(Ref, L1R, L2);
        {l2, Ref, L2R} when L1 == undefined -> receive_results(Ref, L1, L2R);
        {l1, Ref, L1R} -> {L1R, L2};
        {l2, Ref, L2R} -> {L1, L2R}
    after 5000 -> receive_results(Ref, L1, L2)
    end.

do_recv(Socket) ->
    %{ok, {Address, _}} = inet:peername(Socket),
    receive
        {tcp, Socket, List} ->
            try 
                Data = merge_sort(List),
                gen_tcp:send(Socket, Data),
                io:fwrite("Sent sorted list to ~w | Job was done! Goodbye :)~n", [Socket]),
                gen_tcp:close(Socket)
            catch
                _:_ ->
                    io:fwrite("Something went wrong with ~w | Worker terminated and connection closed!~n", [Socket]),
                    gen_tcp:close(Socket)
            end;
        {tcp_closed, _} ->
            io:fwrite("Connection closed ~n");
        {error, _} ->
            io:fwrite("Connection error from ~w | Worker terminated and connection closed!~n", [Socket]),
            gen_tcp:close(Socket)
    end.

Can anyone help me?

Upvotes: 1

Views: 1219

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20014

When you call client:client/0, it creates a connection, sends its data, receives the response, then returns. Meanwhile, the server closes the socket. When you call client:client/0 again, it again creates a connection and sends data, but then it receives the tcp_closed message for the previous socket, and then it returns.

You can fix this by specifying the client socket in your receive patterns:

        receive
            {tcp, Sock, Bin} ->
                io:fwrite("Received sorted list from server: ~w~n", [Bin]);
            {tcp_closed, Sock} ->
                io:fwrite("Connection closed"),
                gen_tcp:close(Sock)
        end;

In this code, the variable Sock replaces both the underscores in the original code, in the {tcp, _, Bin} and {tcp_closed, _} tuples. This forces the messages to match only for the specified socket.

Upvotes: 4

Related Questions