aboutsummaryrefslogtreecommitdiff
path: root/shard/lib/net/tcpserver.ex
blob: 827fefa2ef7162dd56186e15246643fda9ce55bd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
defmodule SNet.TCPServer do
  @moduledoc"""
  Process for accepting TCP connections from peers.
  """

  require Logger
  use Task, restart: :permanent

  def start_link(_) do
    Task.start_link(__MODULE__, :accept, [])
  end

  @doc """
  Starts accepting connections on the given `port`.
  """
  def accept() do
    port = Application.get_env(:shard, :port)
    {: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)
    pid = GenServer.call(SNet.Manager, {:accept, client})
    :ok = :gen_tcp.controlling_process(client, pid)
    loop_acceptor(socket, my_port)
  end
end