8 import java.nio.ByteBuffer;
10 import java.util.concurrent.Semaphore;
13 /** Class IoTSocket is the basic class for IoT RMI
14 * socket communication. This class will be extended
15 * by both IoTSocketServer and IoTSocketClient
17 * Adapted from Java/C++ socket implementation
19 * @see <a href="https://www.keithv.com/software/socket/</a>
21 * @author Rahmadi Trimananda <rtrimana @ uci.edu>
25 public abstract class IoTSocket {
30 protected byte data[];
31 protected int localPort;
33 protected Socket sock;
34 protected BufferedInputStream input;
35 protected BufferedOutputStream output;
37 //protected static Semaphore sendRecvMutex = new Semaphore(1);
42 protected static int BUFFSIZE = 128000; // how many bytes our incoming buffer can hold (original)
43 protected static int MSG_LEN_SIZE = 4; // send length in the size of integer (4 bytes)
48 protected IoTSocket(int _port) throws IOException
52 data = new byte[BUFFSIZE];
56 protected IoTSocket(int _localPort, int _port) throws IOException
58 localPort = _localPort;
60 data = new byte[BUFFSIZE];
65 * sendBytes() sends an array of bytes
67 public synchronized void sendBytes(byte vals[]) throws IOException
69 int len = vals.length;
70 // Write the length first - convert to array of 4 bytes
71 ByteBuffer bb = ByteBuffer.allocate(MSG_LEN_SIZE);
73 output.write(bb.array(), 0, MSG_LEN_SIZE);
75 // Write the byte array
76 output.write(vals, 0, len);
84 * receiveBytes() receives an array of bytes
86 public synchronized byte[] receiveBytes(byte val[]) throws IOException
92 // Wait until input is available
93 if (input.available() == 0) {
97 // Read the maxlen first - read 4 bytes here
98 byte[] lenBytes = new byte[MSG_LEN_SIZE];
99 input.read(lenBytes, 0, MSG_LEN_SIZE);
100 int maxlen = ByteBuffer.wrap(lenBytes).getInt();
101 // Receive until maxlen
102 if (maxlen>BUFFSIZE) {
103 System.out.println("IoTSocketClient/Server: Sending more bytes then will fit in buffer! Number of bytes: " + maxlen);
104 // Allocate a bigger array when needed
106 while (newLen < maxlen) // Shift until we get a new buffer size that's bigger than maxLen (basically power of 2)
107 newLen = newLen << 1;
108 System.out.println("IoTSocketClient/Server: Allocating a bigger buffer now with size: " + newLen);
110 data = new byte[BUFFSIZE];
112 val = new byte[maxlen];
113 while (totalbytes < maxlen)
115 numbytes = input.read(data);
116 // copy the bytes into the result buffer
117 for (i=totalbytes; i<totalbytes+numbytes; i++)
118 val[i] = data[i-totalbytes];
119 totalbytes += numbytes;
121 // we now send an acknowledgement to the server to let them
131 * Close socket connection
133 public void close() throws IOException
142 public synchronized void sendAck() throws IOException
154 public synchronized void receiveAck() throws IOException
157 ack = (int) input.read();
164 public void setSoTimeout(int timeout) throws SocketException {
166 sock.setSoTimeout(timeout);