TCP Echo server(只接收一次连接):
-module(echo).
-export([main/1, start_serv/0]).
start_serv() ->
{ok, Listen} = gen_tcp:listen(2345, [binary, {reuseaddr, true}]),
{ok, Socket} = gen_tcp:accept(Listen),
loop(Socket),
gen_tcp:close(Listen).
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("~p~n", [Bin]),
ok = gen_tcp:send(Socket, Bin),
loop(Socket);
{tcp_closed, Socket} ->
io:format("closed~n")
end.
main(_) ->
start_serv().
TCP Echo server(接受多次连接,处理完一个连接后才能处理第二个连接):
-module(echo).
-compile(export_all).
start_serv() ->
{ok, Listen} = gen_tcp:listen(2345, [binary, {reuseaddr, true}]),
tcp_listen(Listen).
tcp_listen(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
handle_loop(Socket),
tcp_listen(Listen).
handle_loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("~p~n", [Bin]),
ok = gen_tcp:send(Socket, Bin),
handle_loop(Socket);
{tcp_closed, Socket} ->
io:format("closed~n")
end.
main(_) ->
start_serv().
TCP Echo server(并发型,可同时处理多条连接):
-module(echo).
-compile(export_all).
start_serv() ->
{ok, Listen} = gen_tcp:listen(2345, [binary, {reuseaddr, true}]),
tcp_listen(Listen).
tcp_listen(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> tcp_listen(Listen) end),
handle_loop(Socket).
handle_loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("~p~n", [Bin]),
ok = gen_tcp:send(Socket, Bin),
handle_loop(Socket);
{tcp_closed, Socket} ->
io:format("closed~n")
end.
main(_) ->
start_serv().
TCP Echo server(半阻塞):
-module(echo).
-compile(export_all).
start_serv() ->
{ok, Listen} = gen_tcp:listen(2345, [binary,
{active, once},
{reuseaddr, true}]),
tcp_listen(Listen).
tcp_listen(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> tcp_listen(Listen) end),
handle_loop(Socket).
handle_loop(Socket) ->
inet:setopts(Socket, [{active, once}]),
receive
{tcp, Socket, Bin} ->
io:format("~p~n", [Bin]),
ok = gen_tcp:send(Socket, Bin),
handle_loop(Socket);
{tcp_closed, Socket} ->
io:format("closed~n")
end.
main(_) ->
start_serv().
UDP Echo server:
-module(echo).
-compile(export_all).
server() ->
{ok, Socket} = gen_udp:open(2345, [binary]),
loop(Socket).
loop(Socket) ->
receive
{udp, Socket, Host, Port, Bin} ->
gen_udp:send(Socket, Host, Port, Bin),
loop(Socket)
end.
未完待续
网友评论