view src/luan/lib/rpc/RpcCon.java @ 1118:e4710ddfd287

start luan/lib/rpc
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 06 Aug 2017 20:11:11 -0600
parents
children 87c674f3f6b7
line wrap: on
line source

package luan.lib.rpc;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.EOFException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import luan.lib.parser.ParseException;
import luan.lib.json.JsonParser;
import luan.lib.json.JsonToString;


public class RpcCon {
	final Socket socket;
	final InputStream in;
	final OutputStream out;
	InputStream inBinary = null;
	long lenBinary = -1;

	RpcCon(Socket socket) throws IOException {
		this.socket = socket;
		this.in = socket.getInputStream();
		this.out = socket.getOutputStream();
	}

	public void close()
		throws IOException
	{
		socket.close();
	}

	public boolean isClosed() {
		return socket.isClosed();
	}

	void write(InputStream in,long lenIn,List list)
		throws IOException
	{
		if( in != null )
			list.add(0,lenIn);
		String json = JsonToString.toString(list);
		byte[] aJson = json.getBytes(StandardCharsets.UTF_8);
		int len = aJson.length;
		byte[] a = new byte[4+len];
        a[0] = (byte)(len >>> 24);
        a[1] = (byte)(len >>> 16);
        a[2] = (byte)(len >>>  8);
        a[3] = (byte)(len >>>  0);
		System.arraycopy(aJson,0,a,4,len);
		out.write(a);
		if( in != null ) {
			a = new byte[8192];
			long total = 0;
			int n;
			while( (n=in.read(a)) != -1 ) {
				out.write(a,0,n);
				total += n;
			}
			if( total != lenIn )
				throw new IOException("InputStream wrong length "+total+" when should be "+lenIn);
		}
	}

	List readJson()
		throws IOException
	{
		if( inBinary != null ) {
			inBinary.close();
			inBinary = null;
			lenBinary = -1;
		}
		byte[] a = new byte[4];
		readAll(a);
		int len = 0;
		for( byte b : a ) {
			len <<= 8;
			len |= b&0xFF;
		}
		a = new byte[len];
		readAll(a);
		String json = new String(a,StandardCharsets.UTF_8);
		List list;
		try {
			list = (List)JsonParser.parse(json);
		} catch(ParseException e) {
			throw new IOException(e);
		}
		if( list.get(0) instanceof Long ) {
			lenBinary = (Long)list.remove(0);
			inBinary = new FixedLengthInputStream(in,lenBinary);
		}
		return list;
	}

	private void readAll(final byte[] a) throws IOException {
		int total = 0;
		int n;
		while( total < a.length ){
			n = in.read( a, total, a.length-total );
			if( n == -1 )
				throw new EOFException();
			total += n;
		}
	}

}