aboutsummaryrefslogtreecommitdiff
path: root/shard/lib/net/tcpserver.ex
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2018-09-01 16:06:23 +0200
committerAlex Auvolat <alex@adnab.me>2018-09-01 16:06:23 +0200
commitc6ec33d6e612168e14d77007915a4ea423c55a2e (patch)
tree8b5645651a0cc991b8ac9c68c388d84c8dbe73d2 /shard/lib/net/tcpserver.ex
parent1a0ef154a421af60f6d57dfe861dacb844a7d142 (diff)
downloadshard-c6ec33d6e612168e14d77007915a4ea423c55a2e.tar.gz
shard-c6ec33d6e612168e14d77007915a4ea423c55a2e.zip
Move everything to subdirectory
Diffstat (limited to 'shard/lib/net/tcpserver.ex')
-rw-r--r--shard/lib/net/tcpserver.ex26
1 files changed, 26 insertions, 0 deletions
diff --git a/shard/lib/net/tcpserver.ex b/shard/lib/net/tcpserver.ex
new file mode 100644
index 0000000..46552a4
--- /dev/null
+++ b/shard/lib/net/tcpserver.ex
@@ -0,0 +1,26 @@
+defmodule SNet.TCPServer do
+ require Logger
+ use Task, restart: :permanent
+
+ def start_link(port) do
+ Task.start_link(__MODULE__, :accept, [port])
+ end
+
+ @doc """
+ Starts accepting connections on the given `port`.
+ """
+ def accept(port) do
+ {:ok, socket} = :gen_tcp.listen(port,
+ [:binary, packet: 2, active: false, reuseaddr: true])
+ Logger.info "Accepting connections on port #{port}"
+ loop_acceptor(socket, port)
+ end
+
+ defp loop_acceptor(socket, my_port) do
+ {:ok, client} = :gen_tcp.accept(socket)
+ {:ok, pid} = DynamicSupervisor.start_child(Shard.DynamicSupervisor, {SNet.TCPConn, %{socket: client, my_port: my_port}})
+ :ok = :gen_tcp.controlling_process(client, pid)
+ loop_acceptor(socket, my_port)
+ end
+end
+