Gen:tcp socket maximum number of bytes/characters possible to receive

Heh, I’ve written a LOT of TCP and UDP (and SCTP) protocols over the past 25 years, many in erlang itself, so I like to help when I can. ^.^

3 Likes

Interesting post, how would you write the PHP part in Elixir. I actually need it :slight_smile:

:ok = :gen_tcp.send(socket, payload)

I understood I need to add the size of my payload in the 32 firsts bits of what I send but how would I do that ?

As I recall if you set {packet, 4} in the connect then when you :gen_tcp.send/2 it then it should add it automatically. If however you want to do it manually (like you did not specify a packet option at all then you could do:

payload = :erlang.iolist_to_binary(payload) # Do this if it is not already a binary
:ok = :gen_tcp.send(socket, [<<byte_size(payload)::integer-size(32)>>, payload])

Most Erlang IO functions take IO lists, so that is that above. :slight_smile:

You can also bake it into the payload binary itself, but this is slower as it has to copy the entire payload (assuming it is a binary and not an IOlist too):

:ok = :gen_tcp.send(socket, <<byte_size(payload)::integer-size(32), payload::binary>>)

:slight_smile:

Thank you very much !! Indeed I used packet: :line at the beginning and forgot to change it in the connect options :blush:

1 Like