Creating a simple chat server in Erlang, How do I listen for further messages after connection is made

erlang

#1

In order to learn Erlang I decided to build a simple chat server in pure Erlang no libraries, no nothing.

So I have created a server that manages to connect to my client. I know this because I have set up an alert on the connect event.

But how do I continue listening for more messages from the same socket. When I call the receive message recursively then no connection is made with the client and I am at a loss.

I have posted the question on StackOverflow with full source code.

So my questions are how do I listen for more messages on the same socket? Does gen_tcp:send() only send when the socket is closed or about to be closed?

Many Thanks in advance


#2

There are quite a number of examples out there for doing this, have you looked at any?


#3

Yep this is a super-common Erlang example, generally an intro example. :slight_smile:

However, I always went the {active, once} method on the socket and kept telling it when I was ready for me, all wrapped up in a gen_server, which that gen_server was started when the socket was connected to and spawned off, where the listen socket then started listening again. :slight_smile:


#4

Yeah I have had a look at a few of them but the problem that I am having is unique. It seems like there is something up with my program logic or maybe I am not understanding how websockets work correctly.


#5

It might not be the problem here, but you have a race condition with controlling_process. You should send the child process a message (just use an atom like “go”) once controlling_process is done and have the child wait for it before it enters the loop and tries to use the socket. Otherwise there’s no guarantee the child doesn’t try to use the socket before it owns it.

As for debugging this, I would start with a simpler protocol and try it out with telnet.