Erlang:为什么zlib在这里返回一个空体?

时间:2012-03-26 01:17:17

标签: erlang zlib otp

我正在尝试使用zlib压缩发送到客户端的数据。我通常只使用send()向客户端发送一串JSON。这是处理工作的函数:

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;

我的更改很微妙,并且在子句的第一部分中,为了在将Body发送回客户端之前压缩Body,不幸的是,这会返回一个空列表。谁能抓住我在这里做错了什么?我没有看到任何进程崩溃或错误日志中的任何内容。只是一个空列表传递给客户端。

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;

1 个答案:

答案 0 :(得分:3)

你需要在最后一次deflate调用中提供“finish”flush参数,例如: zlib:deflate(Z,Body,finish)