comparison 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
comparison
equal deleted inserted replaced
1117:9a1aa6fc0b4e 1118:e4710ddfd287
1 package luan.lib.rpc;
2
3 import java.io.InputStream;
4 import java.io.OutputStream;
5 import java.io.IOException;
6 import java.io.EOFException;
7 import java.net.Socket;
8 import java.nio.charset.StandardCharsets;
9 import java.util.List;
10 import luan.lib.parser.ParseException;
11 import luan.lib.json.JsonParser;
12 import luan.lib.json.JsonToString;
13
14
15 public class RpcCon {
16 final Socket socket;
17 final InputStream in;
18 final OutputStream out;
19 InputStream inBinary = null;
20 long lenBinary = -1;
21
22 RpcCon(Socket socket) throws IOException {
23 this.socket = socket;
24 this.in = socket.getInputStream();
25 this.out = socket.getOutputStream();
26 }
27
28 public void close()
29 throws IOException
30 {
31 socket.close();
32 }
33
34 public boolean isClosed() {
35 return socket.isClosed();
36 }
37
38 void write(InputStream in,long lenIn,List list)
39 throws IOException
40 {
41 if( in != null )
42 list.add(0,lenIn);
43 String json = JsonToString.toString(list);
44 byte[] aJson = json.getBytes(StandardCharsets.UTF_8);
45 int len = aJson.length;
46 byte[] a = new byte[4+len];
47 a[0] = (byte)(len >>> 24);
48 a[1] = (byte)(len >>> 16);
49 a[2] = (byte)(len >>> 8);
50 a[3] = (byte)(len >>> 0);
51 System.arraycopy(aJson,0,a,4,len);
52 out.write(a);
53 if( in != null ) {
54 a = new byte[8192];
55 long total = 0;
56 int n;
57 while( (n=in.read(a)) != -1 ) {
58 out.write(a,0,n);
59 total += n;
60 }
61 if( total != lenIn )
62 throw new IOException("InputStream wrong length "+total+" when should be "+lenIn);
63 }
64 }
65
66 List readJson()
67 throws IOException
68 {
69 if( inBinary != null ) {
70 inBinary.close();
71 inBinary = null;
72 lenBinary = -1;
73 }
74 byte[] a = new byte[4];
75 readAll(a);
76 int len = 0;
77 for( byte b : a ) {
78 len <<= 8;
79 len |= b&0xFF;
80 }
81 a = new byte[len];
82 readAll(a);
83 String json = new String(a,StandardCharsets.UTF_8);
84 List list;
85 try {
86 list = (List)JsonParser.parse(json);
87 } catch(ParseException e) {
88 throw new IOException(e);
89 }
90 if( list.get(0) instanceof Long ) {
91 lenBinary = (Long)list.remove(0);
92 inBinary = new FixedLengthInputStream(in,lenBinary);
93 }
94 return list;
95 }
96
97 private void readAll(final byte[] a) throws IOException {
98 int total = 0;
99 int n;
100 while( total < a.length ){
101 n = in.read( a, total, a.length-total );
102 if( n == -1 )
103 throw new EOFException();
104 total += n;
105 }
106 }
107
108 }