Question

I am trying to use zlib for compressing data being sent to a client. I typically just send blobs of JSON to the client using send(). Here's the function that handles the work:

handle_tcp({data, RawData}, #s1{socket=Socket}=State) ->
  case decode_and_dispatch(RawData, State#s1.state, Socket) of
    {ok, NewState, Body} ->
      lager:debug("Sending to client decompressed ~p",[Body]),
      send(Socket, Body),
      {noreply, State#s1{state=NewState}};
    {error, _NewState, Msg} ->
      lager:info("calling client_err_msg with ~p~n",[Msg]),
      send(Socket, client_err_msg(Msg)),
      {noreply, State};
    Else ->
      lager:error("Unexpected error: ~p", [Else]),
      send(Socket, client_err_msg(<<"server rejected the message">>)),
      {noreply, State}
  end;

My changes are subtle and are in the first part of the clause in order to compress Body before sending it back to the client, unfortunately this is returning an empty List. Can anyone catch what I'm doing wrong here? I'm not seeing any process crashes or anything in error logs. Just an empty list being passed to the client.

handle_tcp({data, RawData}, #s1{socket=Socket}=State) ->
  case decode_and_dispatch(RawData, State#s1.state, Socket) of
    {ok, NewState, Body} ->
      lager:debug("Sending to client decompressed ~p",[Body]),
      %% compress the payload
      Z = zlib:open(),
      zlib:deflateInit(Z),
      CompressedBody = zlib:deflate(Z,Body),
      lager:debug("Sending to client compressed ~p",[CompressedBody]),
      %%zlib:deflateEnd(Z),
      send(Socket, CompressedBody),
      %%send(Socket, Body),
      {noreply, State#s1{state=NewState}};
    {error, _NewState, Msg} ->
      lager:info("calling client_err_msg with ~p~n",[Msg]),
      send(Socket, client_err_msg(Msg)),
      {noreply, State};
    Else ->
      lager:error("Unexpected error: ~p", [Else]),
      send(Socket, client_err_msg(<<"server rejected the message">>)),
      {noreply, State}
  end;
Was it helpful?

Solution

You need to provide the "finish" flush parameter to the last call of deflate, e.g. zlib:deflate(Z,Body,finish).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top