Created
May 9, 2009 22:17
-
-
Save rsms/109418 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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