Hi,
I’m trying to use the Gun library to connect to Polygon’s socket server, wss://socket.polygon.io/stocks.
This is the response I expect:
> websocat wss://socket.polygon.io/stocks
[{"ev":"status","status":"connected","message":"Connected Successfully"}]
I’ve written a basic wrapper on the Gun library’s methods, as follows:
def connect(ws), do: ws_upgrade(ws)
defp ws_upgrade(%{ path: path, port: port, host: host } = state) do
{:ok, _} = :application.ensure_all_started(:gun)
connect_opts = %{
connect_timeout: :timer.minutes(1),
retry: 10,
retry_timeout: 300
}
case open_connection(host, port, connect_opts) do
{:ok, gun_pid} ->
stream_ref = :gun.ws_upgrade(gun_pid, path)
%{state | stream_ref: stream_ref, gun_pid: gun_pid}
{:error, _ } ->
state
end
end
defp open_connection(host, port, connect_opts) do
with {:ok, conn_pid} <- :gun.open(host, port, connect_opts),
{:ok, _protocol} <- :gun.await_up(conn_pid, :timer.minutes(1)) do
{:ok, conn_pid}
else
{:error, reason} ->
{:error, reason}
end
end
I’ve also added Gun response handlers based on this example.
I’ve tested this with basic examples, like 'echo.websockets.org'
on port 80, and it works just fine. However, when I try with 'socket.polygon.io'
with the path "/stocks"
, I get a gun_response
message with a 308 permanent redirect code. The new location is given by the headers as https://socket.polygon.io/stocks
.
This is a bit confusing to me because WebSockets are only available for HTTP/1.1, or at least that’s what the Gun documentation told me, and this seems to want to redirect me to HTTP/2. Has anyone else had to deal with WebSocket redirects like this before? If so, how did you do it? Thanks!