-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.erl
80 lines (74 loc) · 2.61 KB
/
ring.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
-module(ring).
-export([create/1, addWorker/4, join/5, setPrv/3]).
-include("logging.hrl").
-define(TIMEOUT,2000).
-define(PACKET_TYPE, {packet, 4}).
create(MyPort) ->
{ok, Prv}=gen_tcp:connect("localhost", MyPort, [binary, {active,true}, ?PACKET_TYPE]),
ok=gen_tcp:send(Prv, cmd:make(["IMNXT"])),
receive {tcp, Nxt, <<"IMNXT">>} -> ok end,
{ok, Prv, Nxt}.
addWorker(NxtN, Port, Prv, Nxt) ->
case inet:peername(NxtN) of
{ok,{Ip,_}} ->
SetPrv=cmd:flat(cmd:make(["SETPRV", Ip, Port])),
gen_tcp:send(Nxt, SetPrv),
receive
{tcp, NxtN, <<"OKWORK">>} ->
gen_tcp:close(Nxt),
{ok, Prv, NxtN};
{tcp, Prv, SetPrv} ->
{ok,PrvN}=gen_tcp:connect(Ip, Port, [binary, {active,true}, ?PACKET_TYPE]),
gen_tcp:send(PrvN, cmd:make(["OKPRV"])),
receive
{tcp, NxtN, <<"OKWORK">>} ->
[gen_tcp:close(Con) || Con <- [Prv, Nxt]],
{ok, PrvN, NxtN};
{tcp_close, NxtN} ->
gen_tcp:close(PrvN), continue;
{tcp_close, PrvN} ->
gen_tcp:close(NxtN), continue;
{tcp_close, Prv} ->
[gen_tcp:close(Con) || Con <- [Nxt, PrvN, NxtN]],
reset;
{tcp_close, Nxt} ->
[gen_tcp:close(Con) || Con <- [Prv, PrvN, NxtN]],
reset
after ?TIMEOUT ->
[gen_tcp:close(Con) || Con <- [PrvN, NxtN]],
continue
end;
{tcp_close, NxtN} -> continue;
{tcp_close, Prv} ->
[gen_tcp:close(Con) || Con <- [Nxt, NxtN]],
reset;
{tcp_close, Nxt} ->
[gen_tcp:close(Con) || Con <- [Prv, NxtN]],
reset
after ?TIMEOUT -> gen_tcp:close(NxtN), continue
end;
{error, _} -> gen_tcp:close(NxtN), continue
end.
join(Ip, Port, Prv, Nxt, MyPort) ->
case gen_tcp:connect(Ip, Port, [binary, ?PACKET_TYPE]) of
{ok, PrvN} ->
gen_tcp:send(PrvN, cmd:make(["WORK", MyPort])),
receive
{tcp, NxtN, <<"OKPRV">>} ->
megaphone!disable,
gen_tcp:close(Prv), gen_tcp:close(Nxt),
gen_tcp:send(PrvN, cmd:make(["OKWORK"])),
{ok, PrvN, NxtN};
{tcp_close, PrvN} -> continue
after ?TIMEOUT -> gen_tcp:close(PrvN), continue
end;
{error, _} -> continue
end.
setPrv(Ip, Port, Prv) ->
case gen_tcp:connect(Ip, Port, [binary, ?PACKET_TYPE]) of
{ok,PrvN} ->
ok=gen_tcp:send(PrvN, cmd:make(["OKPRV"])),
gen_tcp:close(Prv),
{ok,PrvN};
{error, _} -> continue
end.