4

我修改了此服务器以使用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.
4

1 回答 1

4

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

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

于 2013-03-25T14:59:37.510 回答