从gen_tcp socket接收特定数量的数据

时间:2012-08-27 09:39:40

标签: erlang gen-tcp

我使用gen_tcp套接字有以下代码,它应该使用{active, true}一些总是大小为5的二进制命令(例如Command = <<"hello">>

{ok, ListenSocket} = gen_tcp:listen(5555,  [{active, true}, {mode, binary}, 
                                            {packet, 0}]),
{ok, Socket} = gen_tcp:accept(ListenSocket),    
loop().

receive() ->
    {tcp, _Socket, Message:4/binary} ->
         io:format("Success~n", []),
         loop();
    {tcp, _Socket, Other} ->
         io:format("Received: ~p~n", [Other]),
         loop()
end.

但是如果我尝试像这样的客户端连接:

1> {ok, S} = gen_tcp:connect("localhost", 5555, []).
   {ok,#Port<0.582>}
2> gen_tcp:send(S, <<"hello">>).
ok

我在接收部分:

Received: {tcp,#Port<0.585>,<<"hello">>}

所以我想我的错误是在模式匹配中...但在哪里?

2 个答案:

答案 0 :(得分:2)

您的receive子句看起来不正确,应该是:

{tcp, _Socket, <<Message:5/binary>>} ->
  ....

答案 1 :(得分:0)

据我了解,您需要gen_tcp:recv功能。来自文档:

recv(Socket, Length) -> {ok, Packet} | {error, Reason}

在您的代码中,它将类似于:

...
{ok, Socket} = gen_tcp:accept(ListenSocket),
loop(Socket).

loop(Socket) -> 
    case gen_tcp:recv(Socket, 5) of
        {ok, Data} ->
            io:format("Success~n", []),
            loop(Socket);
        {error, closed} -> 
            ok
end.