How to Read UDP Data?

I am total new at Phoenix. Just start learning before 2 days. I want to fetch data from UDP Socket that is coming from my C program, That data contain JSON. Then show that data on screen and save into the database.
Something can I found from scratch? Any Video, Any article or post here in forum, I try but didn’t found any thing.

:wave:

You can use :gen_udp.

4 Likes

maybe check this one out https://www.rokkincat.com/blog/2016/05/09/parsing-udp-in-elixir-with-binary-pattern-matching - obviously you want to parse the json - and maybe not use binary matching…

1 Like
defmodule TestZeeshanWeb.PageController do
  use TestZeeshanWeb, :controller
  use GenServer
  
  def start_link(opts \\ []) do
      GenServer.start_link(__MODULE__, :ok, opts)
  end

  def init (:ok) do
      {:ok, _socket} = :gen_udp.open(6789)
  end

  # Handle UDP data
  def handle_info({:udp, socket, ip, _port, data}, state) do
      IO.puts inspect(data)
      
      {:noreply, state}
  end

  # Ignore everything else
  def handle_info({:udp, socket}, state) do
      {:noreply, state}
  end

  def index(conn, _params) do
    render(conn, "index.html")
  end
end

Use this code

2 Likes

You can find a nice and well documented example of a fault tolerant udp server here: https://gist.github.com/joshnuss/08603e11615ee0de65724be4d6335475

5 Likes

I ported the gist into a repo due to it not working as instructed.