How to remove a transport route through Phoenix?

I'm using the Phoenix Chat Room Example and am having some problems with routing.

Inside the user_socket.ex file:

defmodule Chat.UserSocket do
  use Phoenix.Socket

  channel "rooms:*", Chat.RoomChannel

  transport :websocket, Phoenix.Transports.WebSocket

  def connect(_params, socket) do
    {:ok, socket}
  end

  def id(_socket), do: nil
end

The problem I have is under the transport configuration.

transport :websocket, Phoenix.Transports.Websocket

Setting up a transport is basically like a directory. To connect through this socket, the client must have /websocket at the end of their URL. I am trying to gracefully remove that. I'm trying to get my websocket server to be accessed by server:port, with no directory requirements.


I found that the Chat.UserSocket module is called from lib/chat/endpoint.ex:

socket "/Balancer", Chat.UserSocket

Which this socket is also adding another required directory. So, to connect to the websocket server, you would need to append /Balancer/websocket to the URL. I am trying to remove that requirement. I could shorten the words, and use B/W, but that just seems unintuitive. Also, I'm fairly new to Elixir/Phoenix so I apologize for this sloppy question.

Upvotes: 0

Views: 473

Answers (1)

tkowal
tkowal

Reputation: 9289

It is a good idea to have a separate path for your websockets. There are couple of reasons why it is better to use standard 80 or 443 ports Shall I use WebSocket on ports other than 80?

By default socket constructor in java script adds the websocket part, but you can easily assign whatever you want like this:

socket.endPoint = "/ws"

In the endpoint you can then match on root:

socket "/", Chat.UserSocket

and in the user socket you need to use:

transport :ws, Phoenix.Transports.WebSocket

It is totally possible to use "/" without any other paths as a root for your websocket on the JS side, but if you try it in this chat example, you will see that the request matches on Chat.PageController.index. You could try then with empty atom for transport :"", but it is a little hacky and may not work, so I would stick to the /ws path.

Upvotes: 2

Related Questions