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