socket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // NOTE: The contents of this file will only be executed if
  2. // you uncomment its entry in "assets/js/app.js".
  3. // To use Phoenix channels, the first step is to import Socket,
  4. // and connect at the socket path in "lib/web/endpoint.ex".
  5. //
  6. // Pass the token on params as below. Or remove it
  7. // from the params if you are not using authentication.
  8. import {Socket} from "phoenix"
  9. let socket = new Socket("/socket", {params: {token: window.userToken}})
  10. // When you connect, you'll often need to authenticate the client.
  11. // For example, imagine you have an authentication plug, `MyAuth`,
  12. // which authenticates the session and assigns a `:current_user`.
  13. // If the current user exists you can assign the user's token in
  14. // the connection for use in the layout.
  15. //
  16. // In your "lib/web/router.ex":
  17. //
  18. // pipeline :browser do
  19. // ...
  20. // plug MyAuth
  21. // plug :put_user_token
  22. // end
  23. //
  24. // defp put_user_token(conn, _) do
  25. // if current_user = conn.assigns[:current_user] do
  26. // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
  27. // assign(conn, :user_token, token)
  28. // else
  29. // conn
  30. // end
  31. // end
  32. //
  33. // Now you need to pass this token to JavaScript. You can do so
  34. // inside a script tag in "lib/web/templates/layout/app.html.eex":
  35. //
  36. // <script>window.userToken = "<%= assigns[:user_token] %>";</script>
  37. //
  38. // You will need to verify the user token in the "connect/3" function
  39. // in "lib/web/channels/user_socket.ex":
  40. //
  41. // def connect(%{"token" => token}, socket, _connect_info) do
  42. // # max_age: 1209600 is equivalent to two weeks in seconds
  43. // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
  44. // {:ok, user_id} ->
  45. // {:ok, assign(socket, :user, user_id)}
  46. // {:error, reason} ->
  47. // :error
  48. // end
  49. // end
  50. //
  51. // Finally, connect to the socket:
  52. socket.connect()
  53. // Now that you are connected, you can join channels with a topic:
  54. let channel = socket.channel("topic:subtopic", {})
  55. channel.join()
  56. .receive("ok", resp => { console.log("Joined successfully", resp) })
  57. .receive("error", resp => { console.log("Unable to join", resp) })
  58. export default socket