3 import java.io.IOException;
4 import java.net.DatagramPacket;
5 import java.net.DatagramSocket;
6 import java.net.InetAddress;
7 import java.net.SocketException;
8 import java.net.UnknownHostException;
11 /** Class IoTUDP is a wrapper class that provides
12 * minimum interfaces for user to interact with IoT
13 * devices in our system - adapted from my colleague's
14 * work (Ali Younis - ayounis @ uci.edu)
16 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
23 * IoTUDP class properties
25 private final String strHostAddress;
26 private final int iSrcPort;
27 private final int iDstPort;
28 private DatagramSocket socket; // the socket interface that we are guarding
29 private boolean didClose; // make sure that the clean up was done correctly
34 public IoTUDP(IoTDeviceAddress iotDevAdd) throws SocketException, IOException {
36 strHostAddress = iotDevAdd.getHostAddress();
37 iSrcPort = iotDevAdd.getSourcePortNumber();
38 iDstPort = iotDevAdd.getDestinationPortNumber();
40 socket = new DatagramSocket(iSrcPort);
47 * @param bData Byte type that passes the data to be sent
50 public void sendData(byte[] bData) throws UnknownHostException, IOException {
52 DatagramPacket dpSendPacket = new DatagramPacket(bData, bData.length, InetAddress.getByName(strHostAddress), iDstPort);
53 socket.send(dpSendPacket);
57 * recieveData() method
59 * @param iMaxDataLength Integer maximum data length as reference
62 public byte[] recieveData(int iMaxDataLength) throws IOException {
64 byte[] bReceiveData = new byte[iMaxDataLength];
65 DatagramPacket dpReceivePacket = new DatagramPacket(bReceiveData, bReceiveData.length);
66 socket.receive(dpReceivePacket);
68 return dpReceivePacket.getData();
72 * setSoTimeout() method
74 * @param iTimeout Integer timeout time
76 public void setSoTimeout(int iTimeout) throws SocketException {
78 socket.setSoTimeout(iTimeout);
83 * setSendBufferSize() method
85 * @param iSize Integer buffer size
87 public void setSendBufferSize(int iSize) throws SocketException {
89 socket.setSendBufferSize(iSize);
94 * setReceiveBufferSize() method
96 * @param iSize Integer buffer size
98 public void setReceiveBufferSize(int iSize) throws SocketException {
100 socket.setReceiveBufferSize(iSize);
105 * setReuseAddress(boolean on) method
107 public void setReuseAddress(boolean on) throws SocketException {
109 socket.setReuseAddress(on);
115 public void close() {
123 * close() called by the garbage collector right before trashing object
125 public void finalize() throws SocketException {
129 throw new SocketException("Socket not closed before object destruction, must call close method.");