4 import java.io.IOException;
5 import java.net.DatagramPacket;
6 import java.net.DatagramSocket;
7 import java.net.InetAddress;
8 import java.net.SocketException;
9 import java.net.UnknownHostException;
11 import iotruntime.slave.IoTDeviceAddress;
13 /** Class IoTUDP is a wrapper class that provides
14 * minimum interfaces for user to interact with IoT
15 * devices in our system - adapted from my colleague's
16 * work (Ali Younis - ayounis @ uci.edu)
18 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
25 * IoTUDP class properties
27 private final String strHostAddress;
28 private final int iSrcPort;
29 private final int iDstPort;
30 private DatagramSocket socket; // the socket interface that we are guarding
31 private boolean didClose; // make sure that the clean up was done correctly
36 public IoTUDP(IoTDeviceAddress iotDevAdd) throws SocketException, IOException {
38 strHostAddress = iotDevAdd.getHostAddress();
39 iSrcPort = iotDevAdd.getSourcePortNumber();
40 iDstPort = iotDevAdd.getDestinationPortNumber();
42 socket = new DatagramSocket(iSrcPort);
49 * @param bData Byte type that passes the data to be sent
52 public void sendData(byte[] bData) throws UnknownHostException, IOException {
54 DatagramPacket dpSendPacket = new DatagramPacket(bData, bData.length, InetAddress.getByName(strHostAddress), iDstPort);
55 socket.send(dpSendPacket);
59 * recieveData() method
61 * @param iMaxDataLength Integer maximum data length as reference
64 public byte[] recieveData(int iMaxDataLength) throws IOException {
66 byte[] bReceiveData = new byte[iMaxDataLength];
67 DatagramPacket dpReceivePacket = new DatagramPacket(bReceiveData, bReceiveData.length);
68 socket.receive(dpReceivePacket);
70 return dpReceivePacket.getData();
74 * setSoTimeout() method
76 * @param iTimeout Integer timeout time
78 public void setSoTimeout(int iTimeout) throws SocketException {
80 socket.setSoTimeout(iTimeout);
85 * setSendBufferSize() method
87 * @param iSize Integer buffer size
89 public void setSendBufferSize(int iSize) throws SocketException {
91 socket.setSendBufferSize(iSize);
96 * setReceiveBufferSize() method
98 * @param iSize Integer buffer size
100 public void setReceiveBufferSize(int iSize) throws SocketException {
102 socket.setReceiveBufferSize(iSize);
110 public void close() {
118 * close() called by the garbage collector right before trashing object
120 public void finalize() throws SocketException {
124 throw new SocketException("Socket not closed before object destruction, must call close method.");