public class DelimFramer implements Framer
{
private InputStream in;// Data Source
private static final byte DELIMITER = '\n';
public DelimFramer(InputStream in)
{
this.in = in;
}
public void frameMsg(byte[] message, OutputStream out)
throws IOException
{
for (byte b : message)
{
if (b == DELIMITER)
{
throw new IOException("Message Contains DELIMITER");
}
}
out.write(message);
out.write(DELIMITER);
out.flush();
}
public byte[] nextMsg()
throws IOException
{
ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream();
int nextByte;
while ((nextByte = in.read()) != DELIMITER)
{
if (nextByte == -1)
{
if (messageBuffer.size() == 0)
{
return null;
}
else
{
throw new EOFException("Non-Empty Message Without DELIMITER");
}
}
messageBuffer.write(nextByte);
}
return messageBuffer.toByteArray();
}