+ public void run() {
+ // Thread run function; handle OPC traffic.
+ while (Thread.currentThread() == thread) {
+
+ try {
+ Socket cli = server.accept();
+ InputStream input = cli.getInputStream();
+ bufferedByteCount = 0;
+
+ while (Thread.currentThread() == thread) {
+
+ int r = input.read(buffer, bufferedByteCount, buffer.length - bufferedByteCount);
+ if (r <= 0) {
+ break;
+ }
+ bufferedByteCount += r;
+
+ // Extract OPC packets from buffer
+ int offset = 0;
+ while (bufferedByteCount - offset >= 4) {
+ int channel = buffer[offset + 0] & 0xFF;
+ int command = buffer[offset + 1] & 0xFF;
+ int length = ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF);
+
+ if (bufferedByteCount - offset < length + 4) {
+ // Not enough data for a full packet yet
+ break;
+ }
+
+ // Handle the packet in-place
+ offset += 4;
+ opcPacket(channel, command, offset, length);
+ offset += length;
+ }
+
+ // If we didn't use the whole buffer, save remainder for later
+ bufferedByteCount -= offset;
+ arrayCopy(buffer, offset, buffer, 0, bufferedByteCount);
+ }