[erlang-questions] ssl {active, once} {packet, 4}
H.C. v. Stockhausen
hc@REDACTED
Thu Jun 27 07:39:15 CEST 2013
Hi,
this is my first post to this group. Hello everyone.
I am writing a client that connects to a server via ssl:connect. Upon
connection the server returns a <greeting/>. Thereafter the client
sends commands. The protocol has a 4 byte header that specifies the
payload length followed by the xml payload.
Here's an extract of my initial attempt that works:
%%%%%%%%%%%%%%%%%%%%%%%%
...
-behaviour(gen_server).
-define(HEADER_SIZE, 4).
...
init([]) ->
{ok, Socket} = ssl:connect(
<host>, <port>, [
binary,
{active, false},
{keepalive, true},
{certfile, <some/path>},
{keyfile, <some/path>}
]),
{ok, #state{socket=Socket}, 0}.
...
handle_info(timeout, State) ->
{ok, _Greeting} = recv(State#state.socket),
{noreply, State}.
...
% internal helpers
send(Socket, Msg) ->
Length = string:len(Msg) + ?HEADER_SIZE,
Data = <<Length:32, (list_to_binary(Msg))/binary>>,
ok = ssl:send(Socket, Data),
ok.
recv(Socket) ->
{ok, <<Length:32/integer>>} = ssl:recv(Socket, ?HEADER_SIZE),
{ok, Data} = ssl:recv(Socket, Length-?HEADER_SIZE),
Response = binary_to_list(Data),
{ok, Response}.
%%%%%%%%%%%%%%%%%%%%%%%%
I have two questions.
1) As you can see init()/1 has a 0 timeout to trigger
handle_info(timeout, State) which then fetches and discard the
greeting message.
Shouldn't I be able to just set {active, once} instead and handle the
initial server response in a matching handle_info clause? I tried but
it's never triggered. All I receive after a while is
{ssl_closed,{sslsocket,new_ssl,<0.65.0>}}.
2) I manually build and unwrap the header/payload but isn't that what
{packet, 4} is for? I also tried that but the server does not respond,
as incidentally was the case when I initially didn't set the header
properly.
I realise that there are a lot of list_to_binary_to_list_to...
conversions but that's another issue, isn't it?
Is this how {active, once} and {packet, 4} should work or am I missing
something, such as differences when it comes to ssl or client vs.
server behaviour?
Best regards,
Hans Christian
More information about the erlang-questions
mailing list