[erlang-questions] How to write a TCP server in Erlang?

Ulf Wiger (TN/EAB) <>
Fri Jun 15 09:40:57 CEST 2007


 
Per Hedeland wrote:
> 
> Firing off a bunch of messages without intervening
> sleep and then closing the socket should work fine
> per se - this is TCP semantics, and gen_tcp/inet_drv
> should preserve it. Doesn't matter if the receiver
> is "busy", the messages won't get lost 
> unless the *receiver* closes his socket before picking them 
> up, which might be what is happening here:

While that sounds perfectly reasonable, and I'd be
a fool to question your authority on the subject,
I did test removing the close in the server, and 
having it loop instead, and made the client send
10 messages and then immediately close the socket.
The server received one message and then got 
{error, closed}. This didn't happen if I inserted 
a timeout between the sends.

Changing the server from {active,false} to {active,true}
and doing a message trace on it, I can clearly see the
10 incoming messages and then the close, if I have 
a delay inserted between the messages. Without the 
delay, the close comes directly after the first 
message, which btw is the concatenation of all 10 
(short) messages.

So now it is entirely obvious what's happening. (:
As you pointed out the use of {packet,0} was
unfortunate, but in fact because there was 
_more_ than the whole packet in the buffer, and
the recv() did take it all.

I didn't do the tracing the first time, and drew
the wrong conclusion. Here's my revised opinion:

- no (application-level) flow control between
  server and client
- binary_to_term/1 will accept a tail of "garbage"
  as long as the first part of the binary can 
  be decoded into an Erlang term. The rest will
  be ignored. (This is not obvious, and not
  documented, as far as I can tell.)
- The sleep allowed the server to empty the 
  receive buffer and print to tty, so the 
  packets could be handled one by one.

(Obviously based on what I assumed was meant when 
Matej said he tried sending more than one message.)

BR,
Ulf W



More information about the erlang-questions mailing list