Skip to content

Instantly share code, notes, and snippets.

@wangyangkobe
Created September 6, 2015 09:05
Show Gist options
  • Save wangyangkobe/375530a565e7eb9ca826 to your computer and use it in GitHub Desktop.
Save wangyangkobe/375530a565e7eb9ca826 to your computer and use it in GitHub Desktop.
The tcp server of Erlang.
-module(tcp_server).
-compile(export_all).
start(Port) ->
Pid = spawn_link(fun()->
{ok, ListenSocket} = gen_tcp:listen(Port, [binary, {active, false}]),
spawn(fun() -> acceptor(ListenSocket) end),
timer:sleep(infinity)
end),
{ok, Pid}.
acceptor(ListenSocket) ->
{ok, Socket} = gen_tcp:accept(ListenSocket),
spawn(fun() -> acceptor(ListenSocket) end),
handle(Socket).
handle(Socket) ->
inet:setopts(Socket, [{active, once}]),
receive
{tcp, Socket, <<"quit", _/binary>>} ->
gen_tcp:close(Socket);
{tcp, Socket, Message} ->
gen_tcp:send(Socket, Message),
handle(Socket)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment