diff options
Diffstat (limited to 'shard/lib/net/tcpconn.ex')
-rw-r--r-- | shard/lib/net/tcpconn.ex | 25 |
1 files changed, 13 insertions, 12 deletions
diff --git a/shard/lib/net/tcpconn.ex b/shard/lib/net/tcpconn.ex index 67d7f4c..476c426 100644 --- a/shard/lib/net/tcpconn.ex +++ b/shard/lib/net/tcpconn.ex @@ -33,23 +33,21 @@ defmodule SNet.TCPConn do end def init(state) do - if state.is_client do - GenServer.cast(self(), :client_handshake) - else + if Map.has_key?(state, :socket) do GenServer.cast(self(), :server_handshake) + else + GenServer.cast(self(), :client_handshake) end - {:ok, state} end - def handle_call(:get_peer_info, _from, state) do {:reply, state.peer_info, state} end - def handle_cast(:client_handshake, state) do - socket = state.socket + {:inet, ip, port} = state.connect_to + {:ok, socket} = :gen_tcp.connect(ip, port, [:binary, packet: 2, active: false]) net_key = Application.get_env(:shard, :network_key) %{public: cli_eph_pk, secret: cli_eph_sk} = :enacl.box_keypair @@ -150,9 +148,11 @@ defmodule SNet.TCPConn do |> Map.put(:peer_info, {:inet, addr, port}) |> Map.put(:my_port, state.my_port) - GenServer.cast(Shard.Manager, {:peer_up, self(), state.peer_info, state.auth}) - Logger.info "New peer: #{print_id state} at #{inspect addr}:#{port}" + if GenServer.call(SNet.Manager, {:peer_up, self(), state.peer_info, state.auth}) == :redundant do + exit :redundant + end + Logger.info "New peer: #{print_id state} at #{inspect addr}:#{port}" {:noreply, state} end @@ -262,9 +262,11 @@ defmodule SNet.TCPConn do |> Map.put(:peer_info, {:inet, addr, his_port}) |> Map.put(:my_port, state.my_port) - GenServer.cast(Shard.Manager, {:peer_up, self(), state.peer_info, state.auth}) - Logger.info "New peer: #{print_id state} at #{inspect state.peer_info} (#{port})" + if GenServer.call(SNet.Manager, {:peer_up, self(), state.peer_info, state.auth}) == :redundant do + exit :redundant + end + Logger.info "New peer: #{print_id state} at #{inspect state.peer_info} (#{port})" {:noreply, state} end @@ -284,7 +286,6 @@ defmodule SNet.TCPConn do def handle_info({:tcp_closed, _socket}, state) do Logger.info "Disconnected: #{print_id state} at #{inspect state.peer_info}" - GenServer.cast(Shard.Manager, {:peer_down, self(), state.peer_info, state.auth}) exit(:normal) end |