Pregunta

I have read that in Erlang using gen_tcp the data sent over the socket can be aggregated in a single stream. How can i force the socket to send exactly a specific number of bytes?

¿Fue útil?

Solución

TCP is a stream protocol (unlike UDP which is packet oriented) which e.g. means that the receiving application can't tell if the available data comes from one or several send() calls on the client.

You don't really have any control over the number of bytes being sent in a TCP packet, multiple send() calls may result in one TCP packet being received, and one send() call may result in several TCP packets being sent. This is controlled by the OS TCP stack.

In Erlang you can use the the socket option {packet, 1|2|4} to gen_tcp:connect and gen_tcp:listen to create a packet-oriented handling of the TCP data. This inserts a 1,2 or 4 bytes prefix to each send() and the receiving side (assuming it is also erlang and uses the same {packet, N} option) will read data until the sent number of bytes has been received, regardless of how the message was fragmented into TCP packets.

A call to gen_tcp:recv will block until the expected number of bytes has been read. And same for active mode sockets, the message is sent with the expected number of bytes.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top