Last active
January 12, 2020 15:23
-
-
Save wingyplus/0e36facd6ac3fdad77f00b3e4f6605be to your computer and use it in GitHub Desktop.
Practicing Elixir by using exercise from Programming Erlang 2nd edition
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
defmodule FileServer do | |
@doc """ | |
starting FileServer process. | |
""" | |
def start(dir \\ ".") do | |
spawn(FileServer, :loop, [dir]) | |
end | |
def loop(dir) do | |
receive do | |
{client, :list_dir} -> | |
send(client, {self(), :file.list_dir(dir)}) | |
{client, {:get_file, file}} -> | |
full = :filename.join(dir, file) | |
send(client, {self(), :file.read_file(full)}) | |
end | |
end | |
end | |
defmodule FileClient do | |
@doc """ | |
list file and directory on server. | |
""" | |
def ls(server) do | |
send(server, {self(), :list_dir}) | |
receive do | |
{^server, dir} -> dir | |
end | |
end | |
@doc """ | |
get file on server. | |
""" | |
def get_file(server, file) do | |
send(server, {self(), {:get_file, file}}) | |
receive do | |
{^server, content} -> | |
content | |
end | |
end | |
end |
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
defmodule FileServer do | |
@doc """ | |
starting FileServer process. | |
""" | |
def start(dir \\ ".") do | |
spawn(FileServer, :loop, [dir]) | |
end | |
def loop(dir) do | |
receive do | |
{client, :list_dir} -> | |
send(client, {self(), File.ls(dir)}) | |
{client, {:get_file, file}} -> | |
full = Path.join([dir, file]) | |
send(client, {self(), File.read(full)}) | |
end | |
end | |
end | |
defmodule FileClient do | |
@doc """ | |
list file and directory on server. | |
""" | |
def ls(server) do | |
send(server, {self(), :list_dir}) | |
receive do | |
{^server, dir} -> dir | |
end | |
end | |
@doc """ | |
get file on server. | |
""" | |
def get_file(server, file) do | |
send(server, {self(), {:get_file, file}}) | |
receive do | |
{^server, content} -> | |
content | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment