package org.kne.cloud.network.klalb;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;

import org.kne.cloud.network.MultiProtocolSocketAddress;

public class StreamKLALBPacketLink extends AbstractKLALBPacketLink implements KLALBPacketLink {

	@Override
	public String toString() {
		return new MultiProtocolSocketAddress((InetSocketAddress)connectSocket.getLocalSocketAddress())+"←"+new MultiProtocolSocketAddress((InetSocketAddress)connectSocket.getRemoteSocketAddress());
	}

	private Socket connectSocket;
	private KLALBInputStream in;
	private KLALBOutputStream out;
	public StreamKLALBPacketLink(Socket connectSocket) throws IOException {
		this.connectSocket=connectSocket;
		connectSocket.setTcpNoDelay(true);
		setSoTimeout(getDefaultSoTimeout());
		out=new KLALBOutputStream(connectSocket.getOutputStream());
		out.flush();
		in=new KLALBInputStream( connectSocket.getInputStream());
		//connectSocket.setSendBufferSize(1024*1024*1024);
	}
	
	@Override
	public void writeKLALBPacket(KLALBPacket kp) throws IOException {
		out.writeKLALBPacket(kp);
	}
	
	@Override
	public KLALBPacket readKLALBPacket() throws IOException {
		return in.readKLALBPacket();
	}

	@Override
	public void close() throws IOException {
		connectSocket.close();
	}

	@Override
	public boolean isClosed() {
		return connectSocket.isClosed();
	}

	@Override
	public void setSoTimeout(int val) throws SocketException {
		connectSocket.setSoTimeout(val);
	}

	@Override
	public int getSoTimeout() throws SocketException {
		return	connectSocket.getSoTimeout();
	}

	@Override
	public void flush() throws IOException {
		out.flush();
	}

	@Override
	public boolean isStream() {
		return true;
	}

	@Override
	public void writePacket(ByteBuffer kp) throws IOException {
		out.writePacket(kp);
	}

	@Override
	public ByteBuffer readPacket() throws IOException {
		return in.readPacket();
	}
	
}
