Aetherus
Why gen_tcp socket closes in binary mode, but keeps open in list mode?
I wrote a GenServer that wraps a gen_tcp socket and does some long running tasks involving reading and writing on the socket.
defmodule MyClient do
use GenServer
@impl true
def init(_) do
{:ok, nil, {:continue, :connect}}
end
@impl true
def handle_continue(:connect, _) do
{:ok, socket} = :gen_tcp.connect(@ip, @port, [
mode: :binary, # <-- NOTICE THIS CONFIG
packet: 0,
keepalive: true,
active: false,
reuseaddr: true,
send_timeout: 5000,
send_timeout_close: true
])
send(self(), :work)
{:noreply, socket}
end
@impl true
def handle_info(:work, socket) do
{:ok, data} = :gen_tcp.recv(socket, 4) # <-- The problematic line
...
{:noreply, socket}
end
end
When I set the mode to :list, it works fine.
When I set the mode to :binary, the line :gen_tcp.recv always returns {:error, :closed}. I wonder why. Did I messed up the configuration?
Marked As Solved
ityonemo
Ok so in my experience that never happens with gen_tcp. TCP packets come with integrity and checking information and the BEAM should respect that and chunk things correctly with recv. However I have seen that happen with tls >= 1.2. Drove me mad. If you are ever expecting to upgrade to tls or are super paranoid, beacuse I don’t 100% know what the beam guarantees are, I recommend not matching at the receive point, just grab all of the binary data and send it to a helper function that can recursively go over the binary (something like this):
def helper(rest), do: :noop
def helper(<<0x68, 0x16, length::.., result::binary-size(length)>> <> rest) do
dispatch(result, length)
helper(rest)
end
def helper(_malformed_binary), do: raise "naughty bytes!"
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









