meh / elixir-socket

Socket wrapping for Elixir.
691 stars 119 forks source link

How can one continuously receive messages on an open WebSocket? #61

Closed sahrizvi closed 8 years ago

sahrizvi commented 8 years ago

Hello @meh ! I am using this library with a WebSocket server and my experience has been very good this far. Thank you! I have a use case where the WebSocket server is sending multiple messages in response to each message sent to it (but independent of the timing of the incoming messages) and I need to capture them all (preferably in the order they are sent by the server). The docs helpfully mention the following way to deal with multiple messages from the server.

socket = Socket.Web.connect! "echo.websocket.org"
case socket |> Socket.Web.recv! do
  {:text, data} ->
    # process data
  {:ping, _ } ->
    socket |> Socket.Web.send!({:pong, ""})
end

However, I believe this will work for only the first message it receives. How can I make this continuously listen for incoming messages, so that I can process them in the order they were sent by the server?

If this is not currently possible (perhaps due to #19 ), could you comment on whether a polling based solution would solve this problem?

sahrizvi commented 8 years ago

Update: This is the polling based solution (credit @sorentwo) I referred to above in the last sentence:

def loop(socket) do
  case socket |> Socket.Web.recv! do
    {:text, data} ->
      # process data
      loop(socket)
    {:ping, _ } ->
      socket |> Socket.Web.send!({:pong, ""})
  end
end
meh commented 8 years ago

Yep, that's exactly how I would do it.

sahrizvi commented 8 years ago

Thanks a lot for the confirmation!