aboutsummaryrefslogtreecommitdiff
path: root/lib/net/tcpserver.ex
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2018-07-03 15:42:17 +0200
committerAlex Auvolat <alex@adnab.me>2018-07-03 15:42:17 +0200
commit8f3009715ee9ccdd7ecb54fea1244a32a29b62c0 (patch)
tree416fb96c39effa4217864bb6a93243803ba8edba /lib/net/tcpserver.ex
downloadshard-8f3009715ee9ccdd7ecb54fea1244a32a29b62c0.tar.gz
shard-8f3009715ee9ccdd7ecb54fea1244a32a29b62c0.zip
Initialize shard repo with code from somewhere
Diffstat (limited to 'lib/net/tcpserver.ex')
-rw-r--r--lib/net/tcpserver.ex35
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/net/tcpserver.ex b/lib/net/tcpserver.ex
new file mode 100644
index 0000000..e5ee996
--- /dev/null
+++ b/lib/net/tcpserver.ex
@@ -0,0 +1,35 @@
+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)
+ end
+
+ defp loop_acceptor(socket) do
+ {:ok, client} = :gen_tcp.accept(socket)
+ {:ok, pid} = DynamicSupervisor.start_child(SNet.ConnSupervisor, {SNet.TCPConn, %{socket: client}})
+ :ok = :gen_tcp.controlling_process(client, pid)
+ loop_acceptor(socket)
+ end
+
+ def add_peer(ip, port) do
+ {:ok, client} = :gen_tcp.connect(ip, port, [:binary, packet: 2, active: false])
+ {:ok, pid} = DynamicSupervisor.start_child(SNet.ConnSupervisor, {SNet.TCPConn, %{socket: client}})
+ :ok = :gen_tcp.controlling_process(client, pid)
+ pid
+ end
+
+end
+