-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMulticastClient.java
More file actions
85 lines (76 loc) · 3 KB
/
MulticastClient.java
File metadata and controls
85 lines (76 loc) · 3 KB
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
81
82
83
84
85
import java.net.MulticastSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.io.IOException;
import java.util.Scanner;
/**
* The MulticastClient class joins a multicast group and loops receiving
* messages from that group. The client also runs a MulticastUser thread that
* loops reading a string from the keyboard and multicasting it to the group.
* <p>
* The example IPv4 address chosen may require you to use a VM option to
* prefer IPv4 (if your operating system uses IPv6 sockets by default).
* <p>
* Usage: java -Djava.net.preferIPv4Stack=true MulticastClient
*
* @author Raul Barbosa
* @version 1.0
*/
public class MulticastClient extends Thread {
private String MULTICAST_ADDRESS = "224.0.224.0";
private int PORT = 4321;
public static void main(String[] args) {
MulticastClient client = new MulticastClient();
client.start();
MulticastUser user = new MulticastUser();
user.start();
}
public void run() {
MulticastSocket socket = null;
try {
socket = new MulticastSocket(PORT); // create socket and bind it
InetAddress group = InetAddress.getByName(MULTICAST_ADDRESS);
socket.joinGroup(group);
while (true) {
byte[] buffer = new byte[10000]; //256
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//socket.setTimeToLive(255);
socket.receive(packet);
System.out.println("Received packet from " + packet.getAddress().getHostAddress() + ":" + packet.getPort() + " with message:");
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
class MulticastUser extends Thread {
private String MULTICAST_ADDRESS = "224.0.224.0";
private int PORT = 4321;
public MulticastUser() {
super("User " + (long) (Math.random() * 1000));
}
public void run() {
MulticastSocket socket = null;
System.out.println(this.getName() + " ready...");
try {
socket = new MulticastSocket(); // create socket without binding it (only for sending)
Scanner keyboardScanner = new Scanner(System.in);
while (true) {
String readKeyboard = keyboardScanner.nextLine();
byte[] buffer = readKeyboard.getBytes();
InetAddress group = InetAddress.getByName(MULTICAST_ADDRESS);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, PORT);
//socket.setTimeToLive(255);
socket.send(packet);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}