tcp.ex (2080B)
1 defmodule Mint.Core.Transport.TCP do 2 @moduledoc false 3 4 @behaviour Mint.Core.Transport 5 6 @transport_opts [ 7 packet: :raw, 8 mode: :binary, 9 active: false 10 ] 11 12 @default_timeout 30_000 13 14 @impl true 15 def connect(address, port, opts) when is_binary(address), 16 do: connect(String.to_charlist(address), port, opts) 17 18 def connect(address, port, opts) do 19 opts = Keyword.delete(opts, :hostname) 20 21 timeout = Keyword.get(opts, :timeout, @default_timeout) 22 inet6? = Keyword.get(opts, :inet6, false) 23 24 opts = 25 opts 26 |> Keyword.merge(@transport_opts) 27 |> Keyword.drop([:alpn_advertised_protocols, :timeout, :inet6]) 28 29 if inet6? do 30 # Try inet6 first, then fall back to the defaults provided by 31 # gen_tcp if connection fails. 32 case :gen_tcp.connect(address, port, [:inet6 | opts], timeout) do 33 {:ok, socket} -> 34 {:ok, socket} 35 36 _error -> 37 wrap_err(:gen_tcp.connect(address, port, opts, timeout)) 38 end 39 else 40 # Use the defaults provided by gen_tcp. 41 wrap_err(:gen_tcp.connect(address, port, opts, timeout)) 42 end 43 end 44 45 @impl true 46 def upgrade(socket, _scheme, _hostname, _port, _opts) do 47 {:ok, socket} 48 end 49 50 @impl true 51 def negotiated_protocol(_socket), do: wrap_err({:error, :protocol_not_negotiated}) 52 53 @impl true 54 def send(socket, payload) do 55 wrap_err(:gen_tcp.send(socket, payload)) 56 end 57 58 @impl true 59 defdelegate close(socket), to: :gen_tcp 60 61 @impl true 62 def recv(socket, bytes, timeout) do 63 wrap_err(:gen_tcp.recv(socket, bytes, timeout)) 64 end 65 66 @impl true 67 def controlling_process(socket, pid) do 68 wrap_err(:gen_tcp.controlling_process(socket, pid)) 69 end 70 71 @impl true 72 def setopts(socket, opts) do 73 wrap_err(:inet.setopts(socket, opts)) 74 end 75 76 @impl true 77 def getopts(socket, opts) do 78 wrap_err(:inet.getopts(socket, opts)) 79 end 80 81 @impl true 82 def wrap_error(reason) do 83 %Mint.TransportError{reason: reason} 84 end 85 86 defp wrap_err({:error, reason}), do: {:error, wrap_error(reason)} 87 defp wrap_err(other), do: other 88 end