Search code examples
socketserlanggen-tcp

Receiving TCP packets as messages instead of using gen_tcp:recv/2


I'm writing a distributed chat application in Erlang for my own learning/benefit. I have a client and a server which maintain a persistent TCP connection. The client initiates the connection using gen_tcp:connect/3. The server is actually distributed over several nodes.

The gen_tcp documentation says:

Packets can be sent to the returned socket Socket using send/2. Packets sent from the peer are delivered as messages:

{tcp, Socket, Data}

Because of this, my client is able to receive any data the server sends as a normal Erlang message. This is desirable for my application.

The problem is that I can't see any way to make the connection on the server act the same way. I would love it if my server could receive sent data as an Erlang message. This way, the server can send data (i.e. when another person in the chat room sends a message) while waiting for the client to send a message.

Is there any way to implement this behavior?

EDIT: I'm aware of prim_inet:async_accept/2, but I'd prefer a documented approach if possible.


Solution

  • Look at inet:setopts with option {active, once|true}. Good article about