Skip to content

Instantly share code, notes, and snippets.

@seanmor5
Created June 21, 2023 16:01
Show Gist options
  • Save seanmor5/15b4e05c94902a22e98138f3fc77ebf2 to your computer and use it in GitHub Desktop.
Save seanmor5/15b4e05c94902a22e98138f3fc77ebf2 to your computer and use it in GitHub Desktop.
defmodule Client do
def main(pid) do
cmd = IO.gets("Enter a command: ") |> String.trim()
case String.split(cmd) do
["show"] ->
key = self()
Task.async(fn ->
send(pid, {:list, key, self()})
receive do
{:io, msg} -> IO.puts(msg)
end
end)
|> Task.await()
main(pid)
["create" | todo] ->
send(pid, {:create, Enum.join(todo, " "), self()})
main(pid)
[action, idx] when action in ~w(complete delete)s ->
{todo_to_delete, _} = Integer.parse(idx)
send(pid, {:delete, todo_to_delete, self()})
main(pid)
["exit"] ->
send(pid, {:kill, self()})
Process.exit(self(), :kill)
_ ->
IO.puts("Invalid command")
main(pid)
end
end
end
defmodule Server do
def main() do
receive do
{:list, key, pid} ->
todos = Process.get(key) || []
send(pid, {:io, Enum.join(todos, "\n")})
main()
{:create, todo, pid} ->
todos = Process.get(pid) || []
Process.put(pid, [todo | todos])
main()
{:complete, todo_to_delete, pid} ->
todos = Process.get(pid) || []
todos = List.delete_at(todos, todo_to_delete)
Process.put(pid, todos)
main()
{:delete, todo_to_delete, pid} ->
todos = Process.get(pid) || []
todos = List.delete_at(todos, todo_to_delete)
Process.put(pid, todos)
main()
{:kill, pid} ->
Process.put(pid, nil)
main()
end
end
end
case System.argv() do
["client"] ->
Client.main({:server, :"server@computer"})
["server"] ->
Process.register(self(), :server)
Server.main()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment