-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMulticastHandler.java
61 lines (43 loc) · 1.77 KB
/
MulticastHandler.java
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
import java.io.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MulticastHandler{
private String multicast_address;
private int multicast_port;
public MulticastHandler(Address multicast_address) {
this.multicast_address = multicast_address.getAddress();
this.multicast_port = multicast_address.getPort();
}
public Message listenMulticastMessages() throws IOException, ClassNotFoundException {
//Create Socket
InetAddress group = InetAddress.getByName(this.multicast_address);
MulticastSocket socket = new MulticastSocket(this.multicast_port);
socket.joinGroup(group);
//Create buffer
byte[] buffer = new byte[1024];
socket.receive(new DatagramPacket(buffer, 1024, group, this.multicast_port));
//Deserialize object
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
ObjectInputStream ois = new ObjectInputStream(bais);
Message message = (Message) ois.readObject();
//Close socket
socket.close();
return message;
}
public void sendMulticastMessage(Message message) throws IOException {
//Create socket
MulticastSocket socket = new MulticastSocket();
InetAddress group = InetAddress.getByName(this.multicast_address);
socket.joinGroup(group);
//Prepare data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(message);
byte[] data = baos.toByteArray();
//Send data
socket.send(new DatagramPacket(data, data.length, group, this.multicast_port));
//Close socket
socket.close();
}
}