Here is a basic erlang echo server.
-module(echo).
-author('Li Chao <lichao1@boco.com.cn>').
-export([listen/1]).
-define(TCP_OPTIONS, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]).
listen(Port) ->
{ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS),
accept(LSocket).
accept(LSocket) ->
{ok, Socket} = gen_tcp:accept(LSocket),
spawn(fun() -> loop(Socket) end),
accept(LSocket).
loop(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, <<"bye\n">>} ->
gen_tcp:send(Socket, list_to_binary("bye buddy!"));
{ok, Data} ->
io:format("~p~n", [Data]),
RecvStr = binary_to_list(Data),
Answer = "you say: " ++ RecvStr,
gen_tcp:send(Socket, list_to_binary(Answer)),
loop(Socket);
{error, closed} ->
ok
end.
Now you can use echo:listen(1234).
to start this echo server. Using nc <server_host> 1234
to connect the server. And use "bye" to disconnect from server.
Ref:
http://20bits.com/article/network-programming-in-erlang/
http://20bits.com/article/erlang-a-generalized-tcp-server