This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
NTW/hw2/src/transport/Receiver.java

66 lines
2.0 KiB
Java

package transport;
public abstract class Receiver extends Transport {
private boolean writing_allowed = true;
private byte[] rcv_buffer = new byte[1024];
private int rcv_offset;
private int rcv_length;
public Receiver() {
}
public final synchronized int receive(byte[] var1, int var2, int var3) throws InterruptedException {
while(this.rcv_length == 0) {
this.wait();
}
if (this.rcv_length < 0) {
return this.rcv_length;
} else if (this.rcv_length > var3) {
for(int var4 = 0; var4 < var3; ++var4) {
var1[var2 + var4] = this.rcv_buffer[this.rcv_offset + var4];
}
this.rcv_offset += var3;
this.rcv_length -= var3;
this.notifyAll();
return var3;
} else {
var3 = this.rcv_length;
do {
--this.rcv_length;
var1[var2 + this.rcv_length] = this.rcv_buffer[this.rcv_offset + this.rcv_length];
} while(this.rcv_length > 0);
this.notify();
return var3;
}
}
protected final void deliver(byte[] bytes, int offset, int length) {
if (length == 0) {
System.err.println("Receiver: error: deliver was called with zero length.");
} else {
synchronized(this) {
try {
while(this.rcv_length != 0) {
this.wait();
}
for(int i = 0; i < length; ++i) {
this.rcv_buffer[i] = bytes[i + offset];
}
this.rcv_offset = 0;
this.rcv_length = length;
this.notifyAll();
} catch (InterruptedException ignored) {
System.err.println("Receiver.deliver: warning: interrupted while delivering to application. Some data might be lost.");
}
}
}
}
}