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