gen_server and gen_tcp messages
Thu Jun 15 14:15:48 CEST 2006
On Wed, 14 Jun 2006, Andrew Lentvorski wrote:
> Andrew Lentvorski wrote:
> > Is there a way to convince the gen_server to call some code when it gets
> > a gen_tcp message or message which it doesn't recognize? Basically I
> > need to splice some extra message handling code into the existing
> > gen_server receive loop.
> Module:handle_info(Info, State) -> Result
The handle_info method for handling calls from "non-OTP" processes works,
but it still strikes me as a bit of a hack.
The approach that you first mentioned seems cleaner ie
gen_server <-> interface process <-> gen_tcp process
where the interface process exists only to convert messages from the
gen_tcp process (or port etc) into gen_server:calls (or casts).
I like this method because it lets you put a logical box around the OTP
processes where you can say "Everything within this box acts is an
OTP component, interacting with the outside world with this
interface process (X), that react to these sets of messages (X,Y) from
the outside world." As far as I can tell the only disadvantage is the
extra cost of transmission of the data from the outside world through the
Another approach is given in Pete Kazmier's "Writing an Erlang Port using
OTP Principles" tutorial
(http://www.trapexit.org/docs/howto/port_and_otp.html). The gen_server
receives a call from a client using handle_call, calls an external echo
process and then goes into state that waits for the reply, before finally
returning from the handle_call function. This works fine for the case
where the gen_server is the thing doing the calling, but not when the
resource attached to the gen_server can send messages spontaneously (ie
the gen_tcp in you case, or a port connected to an experimental
microcontroller in a problem I was thinking about previously).
Using handle_info is one solution, using an extra interface process is
another (which seems cleaner somehow). Is there a definitive
answer for how to connect a OTP application to non-OTP processes cleanly?
More information about the erlang-questions