+package iotrmi.Java;
+
+// Java libraries
+import java.io.*;
+import java.net.*;
+import java.awt.*;
+import java.util.*;
+
+
+/** Class IoTSocket is the basic class for IoT RMI
+ * socket communication. This class will be extended
+ * by both IoTSocketServer and IoTSocketClient
+ * <p>
+ * Adapted from Java/C++ socket implementation
+ * by Keith Vertanen
+ * @see <a href="https://www.keithv.com/software/socket/</a>
+ *
+ * @author Rahmadi Trimananda <rtrimana @ uci.edu>
+ * @version 1.0
+ * @since 2016-08-17
+ */
+public abstract class IoTSocket {
+
+ /**
+ * Class Properties
+ */
+ protected byte data[];
+ protected int port;
+ protected Socket sock;
+ protected BufferedInputStream input;
+ protected BufferedOutputStream output;
+
+ /**
+ * Class Constant
+ */
+ protected static int BUFFSIZE = 128000; // how many bytes our incoming buffer can hold
+
+ /**
+ * Default constructor
+ */
+ protected IoTSocket(int _port) throws IOException
+ {
+ port = _port;
+ data = new byte[BUFFSIZE];
+ }
+
+
+ /**
+ * sendBytes() sends an array of bytes
+ */
+ public void sendBytes(byte vals[]) throws IOException
+ {
+ int len = vals.length;
+ output.write(len);
+ output.flush();
+ output.write(vals, 0, len);
+ output.flush();
+ receiveAck();
+ sendAck();
+ }
+
+
+ /**
+ * receiveBytes() receives an array of bytes
+ */
+ public byte[] receiveBytes(byte val[]) throws IOException
+ {
+ int i;
+ int totalbytes = 0;
+ int numbytes;
+ // Read the maxlen first
+ int maxlen = (int)input.read();
+ if (maxlen>BUFFSIZE)
+ System.out.println("IoTSocketClient/Server: Sending more bytes then will fit in buffer!");
+ val = new byte[maxlen];
+ while (totalbytes < maxlen)
+ {
+ numbytes = input.read(data);
+ // copy the bytes into the result buffer
+ for (i=totalbytes; i<totalbytes+numbytes; i++)
+ val[i] = data[i-totalbytes];
+ totalbytes += numbytes;
+ }
+ // we now send an acknowledgement to the server to let them
+ // know we've got it
+ sendAck();
+ receiveAck();
+
+ return val;
+ }
+
+
+ /**
+ * Close socket connection
+ */
+ public void close() throws IOException
+ {
+ sock.close();
+ }
+
+
+ /**
+ * Send ACK
+ */
+ public void sendAck() throws IOException
+ {
+ int ack;
+ ack = 0;
+ output.write(ack);
+ output.flush();
+ }
+
+
+ /**
+ * Receive ACK
+ */
+ public void receiveAck() throws IOException
+ {
+ int ack;
+ ack = (int) input.read();
+ }
+}