1 package org.apache.commons.jcs3.utils.discovery;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24
25 import org.apache.commons.jcs3.utils.net.HostNameUtil;
26 import org.apache.commons.jcs3.utils.serialization.StandardSerializer;
27 import org.apache.commons.jcs3.utils.timing.SleepUtil;
28
29 import junit.framework.TestCase;
30
31
32
33
34 public class UDPDiscoveryUnitTest
35 extends TestCase
36 {
37
38
39
40
41 public void testSimpleUDPDiscoveryIPv4()
42 throws IOException
43 {
44 if (HostNameUtil.getMulticastNetworkInterface() == null)
45 {
46 System.out.println("This machine does not support multicast");
47 return;
48 }
49 simpleUDPDiscovery("228.5.6.7");
50 }
51
52
53
54
55
56 public void testSimpleUDPDiscoveryIPv6()
57 throws IOException
58 {
59 if (HostNameUtil.getMulticastNetworkInterface() == null)
60 {
61 System.out.println("This machine does not support multicast");
62 return;
63 }
64
65 simpleUDPDiscovery("FF02::5678");
66 }
67
68
69
70
71
72 private void simpleUDPDiscovery(String discoveryAddress)
73 throws IOException
74 {
75 final UDPDiscoveryAttributes attributes = new UDPDiscoveryAttributes();
76 attributes.setUdpDiscoveryAddr(discoveryAddress);
77 attributes.setUdpDiscoveryPort(6789);
78 attributes.setServicePort(1000);
79 attributes.setUdpTTL(4);
80
81
82 final UDPDiscoveryService service = new UDPDiscoveryService(attributes, new StandardSerializer());
83 service.startup();
84 service.addParticipatingCacheName( "testCache1" );
85
86 final MockDiscoveryListener discoveryListener = new MockDiscoveryListener();
87 service.addDiscoveryListener( discoveryListener );
88
89
90 final UDPDiscoveryReceiver receiver = new UDPDiscoveryReceiver( service,
91 null,
92 attributes.getUdpDiscoveryAddr(),
93 attributes.getUdpDiscoveryPort() );
94 final Thread t = new Thread( receiver );
95 t.start();
96
97
98 try (final UDPDiscoverySender sender = new UDPDiscoverySender(
99 attributes, service.getSerializer()))
100 {
101
102
103 final ArrayList<String> cacheNames = new ArrayList<>();
104 final int numJunk = 10;
105 for ( int i = 0; i < numJunk; i++ )
106 {
107 cacheNames.add( "junkCacheName" + i );
108 }
109 cacheNames.add( "testCache1" );
110
111
112 final int max = 10;
113 int cnt = 0;
114 try
115 {
116 for ( ; cnt < max; cnt++ )
117 {
118 sender.passiveBroadcast( "localhost", 1111, cacheNames, 1 );
119 SleepUtil.sleepAtLeast( 20 );
120 }
121 }
122 catch (IOException e)
123 {
124
125 System.out.println("Problem sending multicast packet: " + e.getMessage());
126 }
127
128 SleepUtil.sleepAtLeast( 200 );
129
130
131 assertTrue( "Receiver count [" + receiver.getCnt() + "] should be the at least the number sent [" + cnt + "].",
132 cnt <= receiver.getCnt() );
133 }
134 }
135 }