[已解决]新手问题badmatch

ccokme 2010-03-21
刚学不久,测试了一个gen_tcp的使用,遇到问题了,代码和erlang programming书的几乎一样,不过就是跑不起来tcp_test:start()报错是:

Error in process with exit value: {{badmatch,{error,closed}},[{tcp_test,par_connect,1}]}

对了几次代码都找不到问题所在

-module(tcp_test).
-export([start/0]).

start() ->
spawn(fun() -> start_listen() end).

start_listen() ->
{ok, Listen} = gen_tcp:listen(1234, [binary, {packet, 0}, {active, true}]),
spawn(fun() -> par_connect(Listen) end).

par_connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> par_connect(Listen) end),
loop(Socket).

loop(Socket) ->
receive
{tcp, Socket, Bin} ->
case inet:peername(Socket) of
{ok, {RemoteIP, _}} ->
io:format("Accept connection from ~p~n", [RemoteIP]);
{error, Why} ->
exit(Why)
end,
io:format("Accept bin ~p~n", [binary_to_term(Bin)]),
gen_tcp:send(Socket, term_to_binary("hello")),
loop(Socket);
Any ->
io:format("Server ~p~n", [Any]),
loop(Socket)
end.
ccokme 2010-03-21
解决了


-module(tcp_test).
-export([start/0]).

start() ->
    spawn(fun() -> start_listen() end).

start_listen() ->
    {ok, Listen} = gen_tcp:listen(1234, [{packet, 0}, {active, true}]),
    Pid = spawn(fun() -> par_connect(Listen) end),
    gen_tcp:controlling_process(Listen, Pid).

par_connect(Listen) ->
    {ok, Socket} = gen_tcp:accept(Listen),
    Pid = spawn(fun() -> par_connect(Listen) end),
    loop(Socket).

loop(Socket) ->
    receive
        {tcp, Socket, Bin} ->
            case inet:peername(Socket) of
                {ok, {RemoteIP, _}} ->
                    io:format("Accept connection from ~p~n", [RemoteIP]);
                {error, Why} ->
                    exit(Why)
            end,
            io:format("Accept bin ~p~n", [Bin]),
            gen_tcp:send(Socket, "you say:"  ++ [Bin] ++ "\r\n"),
            loop(Socket);
        Any ->
            io:format("Server ~p~n", [Any]),
            loop(Socket)
    end.
laputa73 2012-08-14
在erlng shell里面没问题,在命令行就会报错,真抓狂
我也遇到这个问题了,多谢!
怎么发现解决方法的?
Global site tag (gtag.js) - Google Analytics