【问题标题】:Keep Elixir Plug connection open in chunked mode在分块模式下保持 Elixir Plug 连接打开
【发布时间】:2017-04-20 10:01:49
【问题描述】:

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

在请求中,我创建了几个进程,可以说需要 5 秒才能完成,之后我想通过块向客户端发送响应,但连接已关闭

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

“连接”:“保持活动”,“保持活动”:“超时=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

【问题讨论】:

  • 是否可以只打开另一个连接来发送您的回复?

标签: elixir


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多