Application works simple. When it receives request it spawn's thread_listener and loops it 10 times and passes the index (i). ndc_thread takes this data (i) and returns to core. Core is looping and waiting for message from thread, when it receives, it sends chunk containing message returned by thread.
problem is that after that 1..10 loop function is executed it sends "End" chunk and closes connection. So output from curl http://localhost:4000 is: "StartEnd" Desired result is: "Start12345678910End"
Is there any way to keep connection open and wait until custom timeout or wait while processes executed?
defmodule AlivePlug do
import Plug.Conn
def init(opts) do
opts
end
def call(conn, _opts) do
conn = send_chunked(conn, 200)
chunk(conn, "Start")
core_pid = spawn_link(fn -> core_listener(conn) end)
thread = spawn_link(fn -> thread_listener end)
1..10 |> Enum.each(fn i -> send thread, {core_pid, i} end)
chunk(conn, "End")
conn
end
defp core_listener(conn) do
receive do
{status, i} ->
_conn = chunk(conn, Integer.to_string(i))
core_listener(conn)
end
end
defp thread_listener do
receive do
{core_pid, i} ->
send core_pid, {:ok, i}
thread_listener
_ ->
thread_listener
end
end
end
this is working application just run and use with postman or curl http://localhost:4000 https://github.com/programisti/keep-alive-elixir