root / multicastchannels / BackupChannel.java @ 12
History | View | Annotate | Download (1.7 KB)
1 | 12 | up20160473 | package multicastchannels; |
---|---|---|---|
2 | import server.Server; |
||
3 | import threads.messageManagement; |
||
4 | |||
5 | import java.io.IOException; |
||
6 | import java.net.*; |
||
7 | import java.util.Arrays; |
||
8 | |||
9 | public class BackupChannel implements Runnable { |
||
10 | private String INET_ADDR; |
||
11 | private int PORT; |
||
12 | private InetAddress address; |
||
13 | |||
14 | public BackupChannel(String adr, int args) { |
||
15 | this.INET_ADDR = adr;
|
||
16 | this.PORT = args;
|
||
17 | } |
||
18 | |||
19 | public void sendMessage(byte[] message) throws IOException { |
||
20 | DatagramSocket socket = new DatagramSocket(); |
||
21 | InetAddress group = InetAddress.getByName(INET_ADDR); |
||
22 | DatagramPacket packet = new DatagramPacket(message, message.length, group, PORT); |
||
23 | socket.send(packet); |
||
24 | socket.close(); |
||
25 | } |
||
26 | |||
27 | |||
28 | public void receiveMessage(String ip, int port) throws IOException { |
||
29 | byte[] buffer = new byte[1024]; |
||
30 | MulticastSocket socket = new MulticastSocket(PORT); |
||
31 | InetAddress group = InetAddress.getByName(INET_ADDR); |
||
32 | socket.joinGroup(group); |
||
33 | |||
34 | System.out.println("Waiting for multicast message..."); |
||
35 | DatagramPacket packet = new DatagramPacket(buffer, buffer.length); |
||
36 | socket.receive(packet); |
||
37 | String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); |
||
38 | System.out.println("Multicast message received " + msg); |
||
39 | |||
40 | byte[] bufferCopy = Arrays.copyOf(buffer, packet.getLength()); |
||
41 | Server.getThreadLauncher().execute(new messageManagement(bufferCopy));
|
||
42 | |||
43 | socket.leaveGroup(group); |
||
44 | socket.close(); |
||
45 | } |
||
46 | |||
47 | @Override
|
||
48 | public void run() { |
||
49 | try {
|
||
50 | receiveMessage(INET_ADDR, PORT); |
||
51 | } catch (IOException ex) { |
||
52 | ex.printStackTrace(); |
||
53 | } |
||
54 | } |
||
55 | } |