erlang - How to use gen_udp to build udp server to display online clients? -


i erlang newbie. try use gen_udp build server maintain online client online/offline status. clients send udp data udp server, server receive udp data clients, if server not receive data in 5 seconds, server mark client offline.

-module(client_states_manager). -export([start/0]).  start() ->         spawn(fun() -> server(8080) 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 ~w~n",[bin, host]),  %%% how detect if host in list variable (lists:member), if host not in onlinehosts variable, lists:append onlinehosts                                                   %gen_udp:send(socket, host, port, bin),                         loop(socket)         end.   displayonlinehosts(hosts) ->         io:format("there online hosts ~p~n",[hosts]). 

this client ruby script test:

require "socket"  sender = udpsocket.new host = argv[0] port = argv[1] || 8080  puts "connect #{host}:#{port}"  n = 0 loop     sender.send("message #{n}", 0, host, port)     n = n + 1 end 

who give me inspirations started? much.

you have have onlinehosts variable passed loop function , update value accordingly. this:

server(port) ->         {ok, socket} = gen_udp:open(port, [binary, {active, false}]),         io:format("server opened socket:~p~n",[socket]),         loop(socket, []).  loop(socket, onlinehosts) ->         inet:setopts(socket, [{active, once}]),         receive                 {udp, socket, host, port, bin} ->                         io:format("server received:~p ~w~n",[bin, host]),  %%% how detect if host in list variable (lists:member), if host not in onlinehosts variable, lists:append onlinehosts                         case lists:member(host, onlinehosts) of                              true ->                                   loop(socket, onlinehosts);                              false ->                                   %gen_udp:send(socket, host, port, bin),                                   loop(socket, [host | onlinehosts])                         end         end. 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -