Skip to content

Instantly share code, notes, and snippets.

@rsms
Created May 9, 2009 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsms/109418 to your computer and use it in GitHub Desktop.
Save rsms/109418 to your computer and use it in GitHub Desktop.
% simple TCP secho server in Erlang
-module(tcp_echo_server).
-export([run/1]).
-define(TCPOPTS, [binary, {packet,0}, {active,false}, {reuseaddr,true}]).
% Call tcp_echo_server:run(Port) to start the service.
run(Port) ->
run(Port, {127,0,0,1}).
run(Port, IpAddress) ->
{ok, LSocket} = gen_tcp:listen(Port, ?TCPOPTS ++ [{ip, IpAddress}]),
accept(LSocket).
% Wait for incoming connections and spawn the communicate loop
% when we get one.
accept(LSocket) ->
{ok, Socket} = gen_tcp:accept(LSocket),
spawn(fun() -> communicate(Socket) end),
accept(LSocket).
% Echo back whatever data we receive on Socket.
communicate(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
gen_tcp:send(Socket, Data),
communicate(Socket);
{error, closed} ->
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment