root / multicastchannels / RemoteChannel.java @ 12
History | View | Annotate | Download (1.69 KB)
1 |
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 RemoteChannel implements Runnable { |
12 |
private String INET_ADDR; |
13 |
private int PORT; |
14 |
private InetAddress address; |
15 |
|
16 |
public RemoteChannel(String adr, int port) { |
17 |
this.INET_ADDR = adr;
|
18 |
this.PORT = port;
|
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 |
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 |
|
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 |
|
46 |
socket.leaveGroup(group); |
47 |
socket.close(); |
48 |
} |
49 |
|
50 |
@Override
|
51 |
public void run() { |
52 |
try {
|
53 |
receiveMessage(INET_ADDR, PORT); |
54 |
} catch (IOException ex) { |
55 |
ex.printStackTrace(); |
56 |
} |
57 |
} |
58 |
} |