Skip to content

Instantly share code, notes, and snippets.

@smanolloff
Last active August 29, 2015 14:22
Show Gist options
  • Save smanolloff/ec2e9c6f071dbd231862 to your computer and use it in GitHub Desktop.
Save smanolloff/ec2e9c6f071dbd231862 to your computer and use it in GitHub Desktop.
defmodule KVServer do
use Application
def start(_type, _args) do
import Supervisor.Spec
children = [
supervisor(Task.Supervisor, [[name: KVServer.TaskSupervisor]]),
worker(Task, [KVServer, :accept, [4040]])
]
opts = [strategy: :one_for_one, name: KVServer.Supervisor]
Supervisor.start_link(children, opts)
end
def accept(port) do
{:ok, socket} =:gen_tcp.listen(port, [:binary, packet: :line, active: false])
IO.puts "Accepting connections on port #{port}"
loop_acceptor(socket)
end
defp loop_acceptor(socket) do
{:ok, client} = :gen_tcp.accept(socket)
{:ok, pid} = Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
:gen_tcp.controlling_process(client, pid)
# deliberately fail after 10 sec
:timer.sleep(10_000)
1 = 2
loop_acceptor(socket)
end
defp serve(client) do
client
|> read_line()
|> write_line(client)
serve(client)
end
defp read_line(socket) do
{:ok, data} = :gen_tcp.recv(socket, 0)
data
end
defp write_line(line, socket) do
:gen_tcp.send(socket, line)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment