2

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

1 回答 1

3

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

于 2013-03-24T19:00:53.513 回答