Created
September 6, 2015 09:05
-
-
Save wangyangkobe/375530a565e7eb9ca826 to your computer and use it in GitHub Desktop.
The tcp server of Erlang.
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
-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