My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
import java.net.*;

public final class MultiCastReceiver
implements Runnable
{
public static final int BUFFER_SIZE = 1500;

private static volatile long messageCounter = 0L;
private static long lastMessageCounter = 0L;
private static long lastTimestamp = System.currentTimeMillis();

public static void main(final String[] args)
throws Exception
{
init(args);

final int multiCastPort = 4447;
final String address = args[0];
final NetworkInterface networkInterface = NetworkInterface.getByName(args[1]);
final MulticastSocket receiveSocket = new MulticastSocket(multiCastPort);
final SocketAddress socketAddress = new InetSocketAddress(address, multiCastPort);

receiveSocket.joinGroup(socketAddress, networkInterface);

final byte[] buffer = new byte[BUFFER_SIZE];
final DatagramPacket packet = new DatagramPacket(buffer, BUFFER_SIZE);

new Thread(new MultiCastReceiver()).start();

while (true)
{
packet.setLength(BUFFER_SIZE);
receiveSocket.receive(packet);
++messageCounter;
}
}

private static void init(final String[] args)
{
System.setProperty("java.net.preferIPv4Stack", "true");

if (2 != args.length)
{
System.out.println("Usage: java MultiCastReceiver <multicast address> <interface name>");
System.exit(1);
}
}

public void run()
{
while (true)
{
try
{
Thread.sleep(1000L);
}
catch (InterruptedException ex)
{
break;
}

final long newTimestamp = System.currentTimeMillis();
final long duration = newTimestamp - lastTimestamp;
final long newMessageCounter = messageCounter;
final long numberOfMessages = newMessageCounter - lastMessageCounter;

System.out.format("Received %d messages in %dms\n",
Long.valueOf(numberOfMessages),
Long.valueOf(duration));

lastTimestamp = newTimestamp;
lastMessageCounter = newMessageCounter;
}
}
}

Change log

r2 by mjpt777 on Jul 19, 2011   Diff
Added multicast code
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 2348 bytes, 75 lines

File properties

svn:executable
*
Powered by Google Project Hosting