concept socket in category elixir

appears as: Socket, socket
Phoenix in Action

This is an excerpt from Manning's book Phoenix in Action.

Listing 3.1. The Blog.Web module (lib/blog_web/endpoint.ex), comments removed
defmodule BlogWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :blog                      #1

  socket "/socket", BlogWeb.UserSocket, websocket: true, longpoll: false

  plug Plug.Static,                                         #2
    at: "/", from: :blog, gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)

  if code_reloading? do
    socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
    plug Phoenix.LiveReloader
    plug Phoenix.CodeReloader
  end

  plug Plug.RequestId
  plug Plug.Logger


  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library()
  plug Plug.MethodOverride
  plug Plug.Head

  plug Plug.Session,
    store: :cookie,
    key: "_blog_key",
    signing_salt: "JN+IDg+a"

  plug BlogWeb.Router
end
Listing 12.2. The updated AuctionWeb.UserSocket
defmodule AuctionWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "item:*", AuctionWeb.ItemChannel       #1

  # ...
end

The first line in listing 12.4 simply extracts the Socket class from the phoenix JavaScript library.

Now that you’ve imported the Socket class, you need to instantiate a new instance of the class with the parameters you require. By default, channels communicate over the /socket path of your app (you can customize this in AuctionWeb.Endpoint), so you’ll tell it that that’s the path you’d like to connect over. Furthermore, you pass a userToken as a param. You could use that param for user authentication if you needed or wanted authentication. This is all code that’s generated by Phoenix’s Mix task; you won’t need a userToken in your implementation.

let socket = new Socket("/socket", {params: {token: window.userToken}})

This new Socket instance is referenced via the newly created socket variable.