Last active
April 8, 2021 17:24
-
-
Save joshnuss/c84196b4b6c94a4689e08ce5842b230f to your computer and use it in GitHub Desktop.
Example of a Phoenix channel client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Example of Elixir code consuming a Phoenix channel | |
| # | |
| # 1) Join a room | |
| # 2) Send a message | |
| # 3) Receive a message | |
| # | |
| # Add `socket` to your deps in `mix.exs` | |
| # {:socket, "~> 0.3"} | |
| # | |
| # To run: | |
| # $> mix run phoenix_channel_client.exs | |
| # | |
| defmodule Client do | |
| alias Socket.Web, as: Socket | |
| @path "/socket/websocket?vsn=1.0.0" | |
| @default_port 80 | |
| def connect(host), | |
| do: connect(host, @default_port) | |
| def connect(host, port), | |
| do: Socket.connect!(host, port, path: @path) | |
| def send(socket, data) do | |
| text = Poison.encode!(data) | |
| Socket.send!(socket, {:text, text}) | |
| socket | |
| end | |
| def recv(socket) do | |
| {:text, response} = Socket.recv!(socket) | |
| Poison.decode! response | |
| end | |
| end | |
| socket = Client.connect("127.0.0.1", 4000) | |
| |> Client.send(%{topic: "rooms:lobby", event: "phx_join", payload: %{}, ref: "1"}) | |
| |> Client.send(%{topic: "rooms:lobby", event: "shout", payload: %{message: "hello world"}, ref: "2"}) | |
| Client.recv(socket) |> IO.inspect | |
| Client.recv(socket) |> IO.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment