TCP echo server using "socket" module

Hi guys,

I must be missing something, but I’m unable to make an echo server using socket module, which is faster than the old gen_tcp. Whatever I tried, plain old gen_tcp is still faster.

% https://github.com/treadup/erlang-echo-server/blob/master/echo.erl
% The echo module provides a simple TCP echo server. Users can telnet
% into the server and the sever will echo back the lines that are input by the user.
-module(echo).
-export([accept/1]).

% Starts an echo server listening for incoming connections on the given Port.
accept(Port) ->
    {ok, Socket} = gen_tcp:listen(Port, [binary, {active, true}, {packet, raw}, {reuseaddr, true}]),
    io:format("Echo server listening on port ~p~n", [Port]),
    server_loop(Socket).

% Accepts incoming socket connections and passes then off to a separate Handler process
server_loop(Socket) ->
    {ok, Connection} = gen_tcp:accept(Socket),
    Handler = spawn(fun () -> echo_loop(Connection) end),
    gen_tcp:controlling_process(Connection, Handler),
    io:format("New connection ~p~n", [Connection]),
    server_loop(Socket).

% Echoes the incoming lines from the given connected client socket
echo_loop(Connection) ->
    receive
        {tcp, Connection, Data} ->
	    gen_tcp:send(Connection, Data),
	    echo_loop(Connection);
	{tcp_closed, Connection} ->
	    io:format("Connection closed ~p~n", [Connection])
    end.

Anyone familiar with the new socket module? How can i make this code faster?

2 Likes

I ran into the same issues with socket, it does not achieve expected performance. I recall @potatosalad benchmarking socket vs gen_tcp on UDP (where it had more success), it’d be interesting to try that again.

2 Likes