helper
import java.io.*;
import util.*;
import naccio.library.*;
public class NRegulatedOutputStream extends java.io.FilterOutputStream {
// This stream is constructed based on the OutputStream passed back by
// a Socket object. All normal OutputStream methods get passed along
// to the original OutputStream unless overriden here. The member
// variable "out" is the original OutputStream.
RNetConnection rnc;
// Default constructor overloaded to keep anyone from calling it.
private NRegulatedOutputStream (OutputStream os) {
super (os);
Assert.badBranch ("Network Connection resource must be specified when creatting a network input stream.");
}
// This is the constructor to use.
public NRegulatedOutputStream (OutputStream os, RNetConnection r) {
super (os);
rnc = r;
// NCheck.statusMessage ("Opening output stream to " + r.getRemoteName ());
}
// Overloaded methods:
public void write (int b) throws IOException {
util.Assert.assert (false);
RNetwork.preSendConnection (rnc, 1);
if (RNetwork.quantumSendAvailable () == 0) {
// Just wait until it's legal.
NCheck.statusMessage ("Waiting to limit socket send bandwidth.");
// RNetwork.waitQuantum ();
}
super.write (b);
RNetwork.postSendConnection (rnc, 1);
}
// *** This is the interesting one *** //
public void write (byte b[]) throws IOException {
// Do one piece at a time.
int offset = 0;
do {
int avail = RNetwork.quantumSendAvailable ();
if (avail + offset > b.length) { // can send the rest
avail = b.length - offset;
}
RNetwork.preSendConnection (rnc, avail);
// NCheck.statusMessage ("Sending chunk: " + offset + " - " + avail + " / " + b.length);
super.write (b, offset, avail);
offset += avail;
RNetwork.postSendConnection (rnc, avail);
} while (offset < b.length);
}
public void write (byte b[], int off, int len) throws IOException {
// Do one piece at a time.
int offset = off;
int lenleft = len;
// NCheck.statusMessage ("write: " + off + " / " + len);
do {
int avail = RNetwork.quantumSendAvailable ();
if (avail > lenleft) {
avail = lenleft;
}
RNetwork.preSendConnection (rnc, avail);
// NCheck.statusMessage ("Sending chunk: " + offset + " - " + avail + " / " + lenleft);
super.write (b, offset, avail);
offset += avail;
lenleft -= avail;
RNetwork.postSendConnection (rnc, avail);
} while (lenleft > 0);
}
}
Naccio Home Page
University of Virginia, Computer Science