0

我有以下代码使用 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">>}

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

4

2 回答 2

2

您的receive条款看起来不正确,应该是:

{tcp, _Socket, <<Message:5/binary>>} ->
  ....
于 2012-08-27T13:20:52.097 回答
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.
于 2012-08-27T09:50:24.990 回答