Skip to content

Commit 290e759

Browse files
deep20jainzhendrikse
authored andcommitted
BAEL1053 - deep20jain@gmail.com - Broadcasting and Multicasting in Java (eugenp#2368)
* Adding code for java broadcasting and multicasting * Changing multicast ip * Adding code to iterate thorugh all network interfaces * Formatting again and fixing bug * Applying formatting rules on all classes * Fixing formatting
1 parent 299432d commit 290e759

6 files changed

Lines changed: 301 additions & 0 deletions

File tree

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.baeldung.java.networking.udp.broadcast;
2+
3+
import java.io.IOException;
4+
import java.net.DatagramPacket;
5+
import java.net.DatagramSocket;
6+
import java.net.InetAddress;
7+
import java.net.NetworkInterface;
8+
import java.net.SocketException;
9+
import java.util.ArrayList;
10+
import java.util.Enumeration;
11+
import java.util.List;
12+
import java.util.stream.Collectors;
13+
14+
public class BroadcastingClient {
15+
private DatagramSocket socket;
16+
private InetAddress address;
17+
private int expectedServerCount;
18+
private byte[] buf;
19+
20+
public BroadcastingClient(int expectedServerCount) throws Exception {
21+
this.expectedServerCount = expectedServerCount;
22+
this.address = InetAddress.getByName("255.255.255.255");
23+
}
24+
25+
public int discoverServers(String msg) throws IOException {
26+
initializeSocketForBroadcasting();
27+
copyMessageOnBuffer(msg);
28+
29+
// When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value.
30+
broadcastPacket(address);
31+
32+
return receivePackets();
33+
}
34+
35+
List<InetAddress> listAllBroadcastAddresses() throws SocketException {
36+
List<InetAddress> broadcastList = new ArrayList<>();
37+
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
38+
while (interfaces.hasMoreElements()) {
39+
NetworkInterface networkInterface = interfaces.nextElement();
40+
41+
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
42+
continue;
43+
}
44+
45+
broadcastList.addAll(networkInterface.getInterfaceAddresses()
46+
.stream()
47+
.filter(address -> address.getBroadcast() != null)
48+
.map(address -> address.getBroadcast())
49+
.collect(Collectors.toList()));
50+
}
51+
return broadcastList;
52+
}
53+
54+
private void initializeSocketForBroadcasting() throws SocketException {
55+
socket = new DatagramSocket();
56+
socket.setBroadcast(true);
57+
}
58+
59+
private void copyMessageOnBuffer(String msg) {
60+
buf = msg.getBytes();
61+
}
62+
63+
private void broadcastPacket(InetAddress address) throws IOException {
64+
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
65+
socket.send(packet);
66+
}
67+
68+
private int receivePackets() throws IOException {
69+
int serversDiscovered = 0;
70+
while (serversDiscovered != expectedServerCount) {
71+
receivePacket();
72+
serversDiscovered++;
73+
}
74+
return serversDiscovered;
75+
}
76+
77+
private void receivePacket() throws IOException {
78+
DatagramPacket packet = new DatagramPacket(buf, buf.length);
79+
socket.receive(packet);
80+
}
81+
82+
public void close() {
83+
socket.close();
84+
}
85+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.java.networking.udp.broadcast;
2+
3+
import java.io.IOException;
4+
import java.net.DatagramPacket;
5+
import java.net.DatagramSocket;
6+
import java.net.InetAddress;
7+
import java.net.InetSocketAddress;
8+
9+
public class BroadcastingEchoServer extends Thread {
10+
11+
protected DatagramSocket socket = null;
12+
protected boolean running;
13+
protected byte[] buf = new byte[256];
14+
15+
public BroadcastingEchoServer() throws IOException {
16+
socket = new DatagramSocket(null);
17+
socket.setReuseAddress(true);
18+
socket.bind(new InetSocketAddress(4445));
19+
}
20+
21+
public void run() {
22+
running = true;
23+
24+
while (running) {
25+
try {
26+
DatagramPacket packet = new DatagramPacket(buf, buf.length);
27+
socket.receive(packet);
28+
InetAddress address = packet.getAddress();
29+
int port = packet.getPort();
30+
packet = new DatagramPacket(buf, buf.length, address, port);
31+
String received = new String(packet.getData(), 0, packet.getLength());
32+
if (received.equals("end")) {
33+
running = false;
34+
continue;
35+
}
36+
socket.send(packet);
37+
} catch (IOException e) {
38+
e.printStackTrace();
39+
running = false;
40+
}
41+
}
42+
socket.close();
43+
}
44+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.java.networking.udp.multicast;
2+
3+
import java.io.IOException;
4+
import java.net.DatagramPacket;
5+
import java.net.InetAddress;
6+
import java.net.MulticastSocket;
7+
8+
public class MulticastEchoServer extends Thread {
9+
10+
protected MulticastSocket socket = null;
11+
protected byte[] buf = new byte[256];
12+
protected InetAddress group = null;
13+
14+
public MulticastEchoServer() throws IOException {
15+
socket = new MulticastSocket(4446);
16+
socket.setReuseAddress(true);
17+
group = InetAddress.getByName("230.0.0.0");
18+
socket.joinGroup(group);
19+
}
20+
21+
public void run() {
22+
try {
23+
while (true) {
24+
DatagramPacket packet = new DatagramPacket(buf, buf.length);
25+
socket.receive(packet);
26+
InetAddress address = packet.getAddress();
27+
int port = packet.getPort();
28+
packet = new DatagramPacket(buf, buf.length, address, port);
29+
String received = new String(packet.getData(), 0, packet.getLength());
30+
if (received.equals("end")) {
31+
break;
32+
}
33+
socket.send(packet);
34+
}
35+
socket.leaveGroup(group);
36+
socket.close();
37+
} catch (IOException e) {
38+
e.printStackTrace();
39+
}
40+
}
41+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.java.networking.udp.multicast;
2+
3+
import java.io.IOException;
4+
import java.net.DatagramPacket;
5+
import java.net.DatagramSocket;
6+
import java.net.InetAddress;
7+
8+
public class MulticastingClient {
9+
private DatagramSocket socket;
10+
private InetAddress group;
11+
private int expectedServerCount;
12+
private byte[] buf;
13+
14+
public MulticastingClient(int expectedServerCount) throws Exception {
15+
this.expectedServerCount = expectedServerCount;
16+
this.socket = new DatagramSocket();
17+
this.group = InetAddress.getByName("230.0.0.0");
18+
}
19+
20+
public int discoverServers(String msg) throws IOException {
21+
copyMessageOnBuffer(msg);
22+
multicastPacket();
23+
24+
return receivePackets();
25+
}
26+
27+
private void copyMessageOnBuffer(String msg) {
28+
buf = msg.getBytes();
29+
}
30+
31+
private void multicastPacket() throws IOException {
32+
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
33+
socket.send(packet);
34+
}
35+
36+
private int receivePackets() throws IOException {
37+
int serversDiscovered = 0;
38+
while (serversDiscovered != expectedServerCount) {
39+
receivePacket();
40+
serversDiscovered++;
41+
}
42+
return serversDiscovered;
43+
}
44+
45+
private void receivePacket() throws IOException {
46+
DatagramPacket packet = new DatagramPacket(buf, buf.length);
47+
socket.receive(packet);
48+
}
49+
50+
public void close() {
51+
socket.close();
52+
}
53+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.java.networking.udp.broadcast;
2+
3+
import org.junit.After;
4+
import org.junit.Test;
5+
6+
import java.io.IOException;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class BroadcastIntegrationTest {
11+
private BroadcastingClient client;
12+
13+
@Test
14+
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
15+
int expectedServers = 4;
16+
initializeForExpectedServers(expectedServers);
17+
18+
int serversDiscovered = client.discoverServers("hello server");
19+
assertEquals(expectedServers, serversDiscovered);
20+
}
21+
22+
private void initializeForExpectedServers(int expectedServers) throws Exception {
23+
for (int i = 0; i < expectedServers; i++) {
24+
new BroadcastingEchoServer().start();
25+
}
26+
27+
client = new BroadcastingClient(expectedServers);
28+
}
29+
30+
@After
31+
public void tearDown() throws IOException {
32+
stopEchoServer();
33+
client.close();
34+
}
35+
36+
private void stopEchoServer() throws IOException {
37+
client.discoverServers("end");
38+
}
39+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.java.networking.udp.multicast;
2+
3+
import org.junit.After;
4+
import org.junit.Test;
5+
6+
import java.io.IOException;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class MulticastIntegrationTest {
11+
private MulticastingClient client;
12+
13+
@Test
14+
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
15+
int expectedServers = 4;
16+
initializeForExpectedServers(expectedServers);
17+
18+
int serversDiscovered = client.discoverServers("hello server");
19+
assertEquals(expectedServers, serversDiscovered);
20+
}
21+
22+
private void initializeForExpectedServers(int expectedServers) throws Exception {
23+
for (int i = 0; i < expectedServers; i++) {
24+
new MulticastEchoServer().start();
25+
}
26+
27+
client = new MulticastingClient(expectedServers);
28+
}
29+
30+
@After
31+
public void tearDown() throws IOException {
32+
stopEchoServer();
33+
client.close();
34+
}
35+
36+
private void stopEchoServer() throws IOException {
37+
client.discoverServers("end");
38+
}
39+
}

0 commit comments

Comments
 (0)