Erlang:服务器游标挂在命令行上?

时间:2013-03-24 18:28:12

标签: shell erlang cursor hang

shell中运行的服务器挂起,无法接受任何输入。有没有办法让程序允许输入,同时仍然运行服务器循环来接受传入的连接?

-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.

1 个答案:

答案 0 :(得分:3)

为服务器循环生成进程而不是调用start函数。 Pid = spawn(fun()-> cp1:start() end).