保持Elixir Plug连接以分块模式打开

时间:2016-03-24 15:20:03

标签: elixir

是否可以在分块状态下保持连接打开几秒钟?

在请求中我创建了几个进程,让我们说5秒完成,之后我想通过chunk向客户端发送响应,但是连接已关闭

我正在用邮递员测试这个,我有这个标题:

  

" Connection":" Keep-Alive"," Keep-Alive":" timeout = 10000"

这是我的最小化应用程序,输出总是" InitEnd" 期望的结果是:" Init1234567789End"或类似的东西:

defmodule AlivePlug do
  import Plug.Conn

  def init(opts) do
    opts
  end

  def call(conn, _opts) do
    conn = send_chunked(conn, 200)
    # send initial chunk
    chunk(conn, "Init")

    pid = start_thread
    # create 10 async processes which does somthing for 5 seconds and then sends result via chunk
    1..10
    |> Enum.each(fn num -> 
      send pid, {conn, num}
    end)

    # send End as a symbol of last chunk
    chunk(conn, "End")
    conn
  end

  defp start_thread, do: spawn_link(fn -> thread_listener end)
  defp thread_listener do
    receive do
      {conn, num} ->
        :timer.sleep(5000)
        # problem is here :(
        # chunk returns {:error, :closed}
        {:error, :closed} = chunk(conn, "#{num}")
        thread_listener
      _ -> 
        thread_listener
    end
  end
end

1 个答案:

答案 0 :(得分:0)

作为解决方法,我定期使用conn

receive do
  ...
  after 3000 ->
    # avoid connection close.
    # execute `chunk(conn, ".")` every 3000ms
    chunk(conn, ".")
end

作为附加信息,chunk的第二个参数不应该是空字符串。