erlang分布式入门(二)-UDP Server-Client
程序员文章站
2022-06-14 16:16:08
...
项目中有在UDP协议上提供的服务,需要对服务的性能进行测试和优化,便找了下使用erlang实现的udp的服务端和客户端。
1.udpServer.erl
-module(udpServer). -export([start/0, client/1]). start() -> spawn(fun() -> server(4000) end). server(Port) -> {ok, Socket} = gen_udp:open(Port, [binary, {active, false}]), io:format("server opened socket:~p~n",[Socket]), loop(Socket). loop(Socket) -> inet:setopts(Socket, [{active, once}]), receive {udp, Socket, Host, Port, Bin} -> io:format("server received:~p~n",[Bin]), gen_udp:send(Socket, Host, Port, Bin), loop(Socket) end. % Client code client(N) -> {ok, Socket} = gen_udp:open(0, [binary]), io:format("client opened socket=~p~n",[Socket]), ok = gen_udp:send(Socket, "localhost", 4000, N), Value = receive {udp, Socket, _, _, Bin} -> io:format("client received:~p~n",[Bin]) after 2000 -> 0 end, gen_udp:close(Socket), Value.
2.在一个终端下启动服务器端
[root@centos-183 erlang-learn]# erl Erlang R15B (erts-5.9) [source] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.9 (abort with ^G) 1> c(udpServer). {ok,udpServer} 2> udpServer:start(). <0.39.0> server opened socket:#Port<0.2237> server received:<<"Hello">> 3>
在服务端执行udpServer:start(). 之后在另外一个终端下启动客户端
[root@centos-183 erlang-learn]# erl Erlang R15B (erts-5.9) [source] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.9 (abort with ^G) 1> udpServer:client(<<"Hello">>). client opened socket=#Port<0.608> client received:<<"Hello">> ok 2>