0

I am a erlang newbie. I am try to use gen_udp to build a server to maintain online client online/offline status. All clients send udp data to udp server, server receive udp data from all clients, if server not receive data in 5 seconds, server mark that 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 from ~w~n",[Bin, Host]), 
%%% How to detect if Host is in a list variable (lists:member), if Host is not already in OnlineHosts variable, lists:append it to OnlineHosts                          
                        %gen_udp:send(Socket, Host, Port, Bin),
                        loop(Socket)
        end.


displayOnlineHosts(Hosts) ->
        io:format("There are online hosts ~p~n",[Hosts]).

This is client ruby script for test:

require "socket"

sender = UDPSocket.new
host = ARGV[0]
port = ARGV[1] || 8080

puts "Connect to #{host}:#{port}"

n = 0
loop do
    sender.send("message #{n}", 0, host, port)
    n = n + 1
end

Who will give me some inspirations to get started? Thanks very much.

4

1 回答 1

0

您必须将该OnlineHosts变量传递给您的loop函数并相应地更新其值。大概是这样的:

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 from ~w~n",[Bin, Host]), 
%%% How to detect if Host is in a list variable (lists:member), if Host is not already in OnlineHosts variable, lists:append it to 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.
于 2013-08-02T00:15:09.997 回答