2

The server running in the shell hangs and cannot accept any input. Is there any way to make the program allow input while still running the server loop to accept incoming connections?

-module(cp1).
-export([start/0,accept/1,enter_loop/1,loop/1]).

start() ->

    io:format("Started Server:~n"),
    {ok, Socket} = gen_tcp:listen(4001, [binary, {packet, 0},{reuseaddr, true},{active, false}]),
    accept(Socket).

accept(ListenSocket) ->
    case gen_tcp:accept(ListenSocket) of
        {ok, Socket} ->
            Pid = spawn(fun() ->
                io:format("Connection accepted ~n", []),
                enter_loop(Socket)
            end),
            io:format("Pid ~p~n",[Pid]),
            gen_tcp:controlling_process(Socket, Pid),
            Pid ! ack,
            accept(ListenSocket);
        Error ->
            exit(Error)
    end.

enter_loop(Sock) ->
    %% make sure to acknowledge owner rights transmission finished
    receive ack -> ok end,
    loop(Sock).

loop(Sock) ->
    %% set soscket options to receive messages directly into itself
    inet:setopts(Sock, [{active, once}]),
    receive
        {tcp, Socket, Data} ->
            io:format("Got packet: ~p~n", [Data]),
            io:format("Send packet: ~p~n",[Data]),
            gen_tcp:send(Socket, Data),
            loop(Socket);
        {tcp_closed, Socket} ->
            io:format("Socket ~p closed~n", [Socket]);
        {tcp_error, Socket, Reason} ->
            io:format("Error on socket ~p reason: ~p~n", [Socket, Reason])
    end.
pandoragami
  • 5,387
  • 15
  • 68
  • 116

1 Answers1

3

Spawn a process for server loop instead of calling the start function. Pid = spawn(fun()-> cp1:start() end).

Vinod
  • 2,243
  • 14
  • 18