private final static int MPORT = 8053;
@Test
public void testTwoMulticastPortsAtOnce() throws UnknownHostException, IOException {
System.out.println("Unit Test: testTwoMulticastPortsAtOnce()");
MulticastSocket firstSocket = null;
MulticastSocket secondSocket = null;
try {
String firstMessage = "ping";
String secondMessage = "pong";
InetAddress someInet = InetAddress.getByName(DNSConstants.MDNS_GROUP);
firstSocket = new MulticastSocket(MPORT);
secondSocket = new MulticastSocket(MPORT);
firstSocket.joinGroup(someInet);
secondSocket.joinGroup(someInet);
//
DatagramPacket out = new DatagramPacket(firstMessage.getBytes("UTF-8"), firstMessage.length(), someInet, MPORT);
DatagramPacket inFirst = new DatagramPacket(firstMessage.getBytes("UTF-8"), firstMessage.length(), someInet, MPORT);
DatagramPacket inSecond = new DatagramPacket(firstMessage.getBytes("UTF-8"), firstMessage.length(), someInet, MPORT);
Receive receiveSecond = new Receive(secondSocket, inSecond);
receiveSecond.start();
Receive receiveFirst = new Receive(firstSocket, inSecond);
receiveFirst.start();
firstSocket.send(out);
if (receiveSecond.waitForReceive()) {
Assert.fail("We did not receive the data in the second socket");
}
String fromFirst = new String(inSecond.getData(), "UTF-8");
assertEquals("Expected the second socket to recieve the same message the first socket sent", firstMessage, fromFirst);
// Make sure the first socket had read its own message
if (receiveSecond.waitForReceive()) {
Assert.fail("We did not receive the data in the first socket");
}
// Reverse the roles
out = new DatagramPacket(secondMessage.getBytes("UTF-8"), secondMessage.length(), someInet, MPORT);
inFirst = new DatagramPacket(secondMessage.getBytes("UTF-8"), secondMessage.length(), someInet, MPORT);
receiveFirst = new Receive(firstSocket, inSecond);
receiveFirst.start();
secondSocket.send(out);
if (receiveFirst.waitForReceive()) {
Assert.fail("We did not receive the data in the first socket");
}
String fromSecond = new String(inFirst.getData(), "UTF-8");
assertEquals("Expected the first socket to recieve the same message the second socket sent", secondMessage, fromSecond);
} finally {
if (firstSocket != null) firstSocket.close();
if (secondSocket != null) secondSocket.close();
}
}