Technomenace

Linux, technology, opensource etc.

A Simple Tcp Server in Erlang

Posted at — Jan 21, 2016
-module(tcpserver).
-export([ start/0, start/1, stop/0 ]).

start() ->
	start(9090).

start(Port) ->
	F = fun() ->
				register(tcpserver, self()),
				{ok, LSock} = gen_tcp:listen(Port, [binary]),
				io:format("====> TcpServer listening on localhost, port ~p~n~n", [Port]),
				spawn(fun() -> loop(LSock) end),
				receive
					stop ->
						exit(killed)
				end
		end,
	Pid = spawn(F).

loop(LSock) ->
	{ok, Sock} = gen_tcp:accept(LSock),
	spawn(fun() -> loop(LSock) end),
	get_data(Sock).

get_data(Sock) ->
	receive
		{tcp_closed, Sock} ->
			ok;
		{tcp, Sock, Data} ->
			Res = list_to_binary(lists:flatten(io_lib:fwrite("You said: ~p~n", [Data]))),
			gen_tcp:send(Sock, Res),
			get_data(Sock)
	end.


stop() ->
	whereis(tcpserver) ! stop.

Run:

1> tcpserver:start().
====> TcpServer listening on localhost, port 9090

<0.396.0>

Test:

$ telnet 127.0.0.1 9090
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello
You said: <<"hello\r\n">>
hey!
You said: <<"hey!\r\n">>
this is cool!!
You said: <<"this is cool!!\r\n">>