package org.kne.cloud.network.klalb;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import org.kne.cloud.network.NetworkPacket;
import org.kne.io.KNEChannels;

public class KLALBInputStream extends DataInputStream {
	private ReadableByteChannel channel;
	public KLALBInputStream(InputStream in) throws IOException {
		super(in);
		channel=Channels.newChannel(in);
		byte[]b=new byte[5];
		readFully(b);
		String s=new String(b,"ascii");
		if(!s.equals("KLALB")) {
			throw new StreamCorruptedException("remote protocol is no KLALB format");
		}
		int bv=readInt();
		int mv=readInt();
		int sv=readInt();
		if((bv!=CONST.bversion)||(mv!=CONST.mversion))
			throw new StreamCorruptedException("remote version is V"+bv+"."+mv+",not V"+CONST.bversion+"."+CONST.mversion);
	}
	public KLALBPacket readKLALBPacket() throws IOException {
		int len=readInt();
		return KLALBPacket.readKLALBPacketFromStream(this);
	}
	public ByteBuffer readPacket() throws IOException {
		int len=readInt();
		ByteBuffer bbf=NetworkPacket.bufferAllocator.allocate(len);
		bbf.limit(len);
		KNEChannels.readFully(channel, bbf);
		return bbf;
	}
	
}
