8 import java.nio.ByteBuffer;
11 /** Class IoTSocket is the basic class for IoT RMI
12 * socket communication. This class will be extended
13 * by both IoTSocketServer and IoTSocketClient
15 * Adapted from Java/C++ socket implementation
17 * @see <a href="https://www.keithv.com/software/socket/</a>
19 * @author Rahmadi Trimananda <rtrimana @ uci.edu>
23 public abstract class IoTSocket {
28 protected byte data[];
30 protected Socket sock;
31 protected BufferedInputStream input;
32 protected BufferedOutputStream output;
37 protected static int BUFFSIZE = 128000; // how many bytes our incoming buffer can hold
38 protected static int MSG_LEN_SIZE = 4; // send length in the size of integer (4 bytes)
43 protected IoTSocket(int _port) throws IOException
46 data = new byte[BUFFSIZE];
51 * sendBytes() sends an array of bytes
53 public void sendBytes(byte vals[]) throws IOException
55 int len = vals.length;
56 // Write the length first - convert to array of 4 bytes
57 ByteBuffer bb = ByteBuffer.allocate(MSG_LEN_SIZE);
59 output.write(bb.array(), 0, MSG_LEN_SIZE);
61 // Write the byte array
62 output.write(vals, 0, len);
70 * receiveBytes() receives an array of bytes
72 public byte[] receiveBytes(byte val[]) throws IOException
77 // Wait until input is available
78 while(input.available() == 0);
79 // Read the maxlen first - read 4 bytes here
80 byte[] lenBytes = new byte[MSG_LEN_SIZE];
81 input.read(lenBytes, 0, MSG_LEN_SIZE);
82 int maxlen = ByteBuffer.wrap(lenBytes).getInt();
83 // Receive until maxlen
85 System.out.println("IoTSocketClient/Server: Sending more bytes then will fit in buffer!");
86 val = new byte[maxlen];
87 while (totalbytes < maxlen)
89 numbytes = input.read(data);
90 // copy the bytes into the result buffer
91 for (i=totalbytes; i<totalbytes+numbytes; i++)
92 val[i] = data[i-totalbytes];
93 totalbytes += numbytes;
95 // we now send an acknowledgement to the server to let them
105 * Close socket connection
107 public void close() throws IOException
116 public void sendAck() throws IOException
128 public void receiveAck() throws IOException
131 ack = (int) input.read();