Reputation: 3235
I have the following code using a gen_tcp socket, which should receive using {active, true}
some binary commands that are always of size 5 (e.g. 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.
But if I try to connect as a client like this:
1> {ok, S} = gen_tcp:connect("localhost", 5555, []).
{ok,#Port<0.582>}
2> gen_tcp:send(S, <<"hello">>).
ok
I have in the receiving part:
Received: {tcp,#Port<0.585>,<<"hello">>}
so I suppose my error is in the pattern matching...but where?
Upvotes: 0
Views: 224
Reputation: 5500
Your receive
clause doesn't look right, it should be:
{tcp, _Socket, <<Message:5/binary>>} ->
....
Upvotes: 2
Reputation: 6234
As far as I understood you need gen_tcp:recv
function. From documentation:
recv(Socket, Length) -> {ok, Packet} | {error, Reason}
In your code it will be something like:
...
{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.
Upvotes: 0