View Javadoc

1   /*
2    * $Id: UdpRoundTripTestCase.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.udp.functional;
12  
13  import org.mule.tck.FunctionalTestCase;
14  
15  import java.io.ByteArrayInputStream;
16  import java.io.ByteArrayOutputStream;
17  import java.io.DataInputStream;
18  import java.io.DataOutputStream;
19  import java.io.IOException;
20  import java.net.DatagramPacket;
21  import java.net.DatagramSocket;
22  import java.net.InetAddress;
23  
24  import edu.emory.mathcs.backport.java.util.Arrays;
25  
26  public class UdpRoundTripTestCase extends FunctionalTestCase
27  {
28  
29      protected String getConfigResources()
30      {
31          return "udp-roundtrip-test-config.xml";
32      }
33  
34      public void testSendAndReceiveUDP() throws IOException
35      {
36          int outPort = 61000;
37          int inPort = 61001;
38  
39          // the socket we talk to
40          DatagramSocket socket = new DatagramSocket(inPort, InetAddress.getLocalHost());
41  
42          // prepare outgoing packet
43          ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
44          DataOutputStream dataOut = new DataOutputStream(bytesOut);
45          dataOut.writeFloat(1.0f);
46          dataOut.writeFloat(2.0f);
47          byte[] bytesToSend = bytesOut.toByteArray();
48  
49          DatagramPacket outboundPacket = new DatagramPacket(bytesToSend, bytesToSend.length,
50              InetAddress.getLocalHost(), outPort);
51          socket.send(outboundPacket);
52  
53          // receive whatever came back
54          byte[] receiveBuffer = new byte[bytesToSend.length];
55          DatagramPacket inboundPacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
56          socket.receive(inboundPacket);
57  
58          // compare byte buffers as strings so we get to see the diff
59          assertEquals(Arrays.toString(outboundPacket.getData()), Arrays.toString(inboundPacket.getData()));
60  
61          // make sure the contents are really the same
62          ByteArrayInputStream bytesIn = new ByteArrayInputStream(inboundPacket.getData());
63          DataInputStream dataIn = new DataInputStream(bytesIn);
64          // the delta is only here to make JUnit happy
65          assertEquals(1.0f, dataIn.readFloat(), 0.1f);
66          assertEquals(2.0f, dataIn.readFloat(), 0.1f);
67      }
68  
69  }