Talking to TCP server from shell

Roger Lipscombe roger@REDACTED
Fri Nov 12 09:45:55 CET 2021

Your code works perfectly when I try it, but *only the first time*.
Once the first client disconnects, there's no longer anything looping
over 'accept'.

<0.86.0> 1> c(magnus).
<0.86.0> 2> magnus:start(7777).
Server accepted connection on port 7777
Server received message: "Hello!\r\n"
Server replying: "Echo Hello!\r\n"
Server socket closed - shutting down...

$ telnet localhost 7777
Connected to localhost.
Escape character is '^]'.
Echo Hello!
telnet> q
Connection closed.
$ telnet localhost 7777
telnet: Unable to connect to remote host: Connection refused

On Fri, 12 Nov 2021 at 01:25, Magnus Leone <magnus.falk@REDACTED> wrote:
> Hello,
> I'm working on making a very basic talk about networking, and eventually a webserver, but I thought I'd start with the very basic parts; just a TCP echo server. The thing is that the talk is not specifically about Erlang, I'm just using that as I'm most familiar with it (and hey, if I get some people interested, that's great). So I wanted the client side to be just a regular shell.
> Here is where my problem comes in - I can't seem to get the server process to accept the incoming connection when it comes from a shell. The code is pretty much straight out of Joe's book and it works fine as long as the other side is also an Erlang process. What I've tried so far:
> >telnet localhost 7777
> Trying
> telnet: Unable to connect to remote host: Connection refused
> >netcat localhost 7777
> *no output*
> Does anyone know how I can use bash to connect to a TCP socket in this scenario?
> Cheers,
> Magnus
> start(Port) ->
>     {ok, ListenSocket} =
>         gen_tcp:listen(Port, [list, {packet, 0},
>                                     {reuseaddr, true},
>                                     {active, true}]),
>     {ok, Socket} = gen_tcp:accept(ListenSocket),
>     ok = gen_tcp:close(ListenSocket),
>     io:format("Server accepted connection on port ~p~n", [Port]),
>     loop(Socket).
> loop(Socket) ->
>     receive
>         {tcp, Socket, StringMsg} ->
>             io:format("Server received message: ~p~n", [StringMsg]),
>             Reply = "Echo " ++ StringMsg,
>             io:format("Server replying: ~p~n", [Reply]),
>             gen_tcp:send(Socket, Reply),
>             loop(Socket);
>         {tcp_closed, Socket} ->
>             io:format("Server socket closed - shutting down...~n")
>     end.

More information about the erlang-questions mailing list