View Javadoc

1   /*
2    * $Id: UdpClient.java 22387 2011-07-12 03:53:36Z dirk.olmes $
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.util;
12  
13  import org.mule.tck.junit4.AbstractMuleContextTestCase;
14  
15  import java.io.IOException;
16  import java.net.DatagramPacket;
17  import java.net.DatagramSocket;
18  import java.net.InetAddress;
19  import java.net.SocketException;
20  import java.net.UnknownHostException;
21  
22  public class UdpClient
23  {
24      private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 512;
25  
26      private int port;
27      private InetAddress host;
28      private int soTimeout = AbstractMuleContextTestCase.RECEIVE_TIMEOUT;
29      private int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
30      private DatagramSocket socket;
31  
32      public UdpClient(int port) throws UnknownHostException
33      {
34          super();
35          this.port = port;
36          this.host = InetAddress.getByName("localhost");
37      }
38  
39      public byte[] send(String string) throws IOException
40      {
41          return send(string.getBytes());
42      }
43  
44      public byte[] send(byte[] bytes) throws IOException
45      {
46          dispatch(bytes);
47  
48          byte[] receiveBuffer = new byte[receiveBufferSize];
49          DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);
50          socket.receive(packet);
51  
52          return packet.getData();
53      }
54  
55      public void dispatch(byte[] bytes) throws IOException
56      {
57          initSocket();
58  
59          DatagramPacket packet = new DatagramPacket(bytes, bytes.length, host, port);
60          socket.send(packet);
61      }
62  
63      private void initSocket() throws SocketException
64      {
65          if (socket == null)
66          {
67              socket = new DatagramSocket();
68              socket.setSoTimeout(soTimeout);
69          }
70      }
71  
72      public void shutdown()
73      {
74          if (socket != null)
75          {
76              socket.close();
77          }
78      }
79  }