The default Phoenix Endpoint
configures a mount-point for both a websocket and long polling:
defmodule MyAppWeb.Endpoint do
…
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]],
longpoll: [connect_info: [session: @session_options]]
The docs say that this function “defines a websocket/longpoll mount-point for a socket
”, but they don’t go into much detail. How does this work? Under what circumstances would my LiveView client connect to the server via long polling instead of a websocket?
Note: I’m not asking what long polling is. I understand that it’s an alternative way to get real-time communication (or at least the appearance of it) between frontend and backend. What’s not clear to me is when exactly long polling would be used instead of websockets. I can’t find anything in the docs that spells it out.
Does the long-polling functionality exist as a fallback in case websockets don’t work or are unavailable for some reason? If so, under what circumstances would this happen?
2 Likes
Yes, exactly. The fallback was added by default relatively recently, here you find more details:
At 00:00:58 Chris talks about long poll fallback.
(https://www.reddit.com/r/elixir/comments/16mi7qn/comment/k18nhjq/)
The client first tries to connect via WebSocket, and then ping the server to ensure the connection actually works.
If the WS doesn’t work for whatever reason, the client uses the fallback and saves a key to session storage (persistent until the browser is restarted) to go straight to the fallback in future page loads.
The circumstances are many, could be browser support, problems with network proxies messing up with WS messages, etc. Can also happen, many times during development, that the client is trying to connect while the server is down and then eventually sticks to the fallback long poll transport until the session is cleared.
There could also be clients which don‘t support connecting using websockets at all.
can this behavior be configured? I feel it hides the underlying issues that might be preventing WebSocket.
In case we need/want to investigate why WebSocket are not working in a given environment or for specific browser/OS configuration
Yes. At the limit you can have your own transports that “phone home” to give you insight.
AFAIK Chris’ experience at fly.io is that no matter how much they’d try to “fix” WS, there will always be cases out of control like proxies between users and the server.
1 Like