Erlang:gen_tcp:recv()不接收客户端发送的数据包?

时间:2013-03-25 10:01:39

标签: erlang client-server limit packet gen-tcp

我修改this server以使用gen_tcp:recv以便将数据包的字节数限制为50.我注释了行inet:setopts(Socket, [{active, once}]),,因为gen_tcp:recv应该是{active,false}。这是客户端erl shell

2> cp3:client().
exit
3> 

这是服务器端erl shell

4> cp3:server().
Started Server:
<0.46.0>
Accept Server:
Pid <0.48.0>
Connection accepted 
Accept Server:
Loop Server:
5> 

我还想知道如果{tcp_closed, Socket}没有创建套接字,我怎么知道套接字是否以返回值gen_tcp:recv关闭?

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

client() ->
    {ok, Socket} =  gen_tcp:connect("localhost", 4001,[list, {packet, 0}]),
    ok = gen_tcp:send(Socket, "packet"),
    receive
        {tcp,Socket,String} ->
            io:format("Client received = ~p~n",[String]),       
            io:format("Client result = ~p~n",[String]),
            gen_tcp:close(Socket)
        after 1000 ->
            exit        
    end.

server() -> 
    Pid = spawn(fun()-> start() end),
    Pid.

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

accept(ListenSocket) ->
    io:format("Accept Server:~n"),
    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(Socket) ->
    %% make sure to acknowledge owner rights transmission finished
    receive ack -> ok end,
    loop(Socket).

loop(Socket) ->
    %% set socket options to receive messages directly into itself
    %%inet:setopts(Socket, [{active, once}]),
    io:format("Loop Server:~n"),
    case gen_tcp:recv(Socket, 50) of
    {ok, Data} ->  
        case Data of
            <<"packet">> ->                 
                io:format("Server replying = ~p~n",[Data]),   
                gen_tcp:send(Socket, Data),
                loop(Socket)                  
        end;
    {error, Reason} ->      
        io:format("Error on socket ~p reason: ~p~n", [Socket, Reason])          
    end.

1 个答案:

答案 0 :(得分:4)

我对你的问题不太清楚,但上面的代码不起作用。希望以下解答您的问题。您的tcp接收case gen_tcp:recv(Socket, 50) of有一个错误。它等待50个字节读取。查看gen_tcp:recv/2的文档。更改长度(封隔器6的长度,但最好是0)以接收所有字节。

该值不限制数据的大小,但在收到长度为50的数据之前,它不会发回数据。相反,您可能需要接受然后再检查它。