Mercurial > hg > Members > nobuyasu > tightVNCClient
annotate src/myVncClient/MyRfbProto.java @ 99:084adee7699b
befor change
author | Yu Taninari <you@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 24 Oct 2011 23:06:02 +0900 |
parents | 1d1bb77d871b |
children | 2f2f8da71d60 |
rev | line source |
---|---|
17 | 1 package myVncClient; |
45 | 2 |
69 | 3 |
19 | 4 import java.awt.Graphics; |
5 import java.awt.Image; | |
18 | 6 import java.awt.image.BufferedImage; |
65 | 7 import java.io.BufferedInputStream; |
19 | 8 import java.io.BufferedOutputStream; |
15 | 9 import java.io.BufferedReader; |
18 | 10 import java.io.ByteArrayInputStream; |
19 | 11 import java.io.ByteArrayOutputStream; |
65 | 12 import java.io.DataInputStream; |
7 | 13 import java.io.IOException; |
27 | 14 import java.io.InputStream; |
15 | 15 import java.io.InputStreamReader; |
18 | 16 import java.net.BindException; |
10 | 17 import java.net.ServerSocket; |
7 | 18 import java.net.Socket; |
69 | 19 import java.net.UnknownHostException; |
60 | 20 import java.nio.ByteBuffer; |
21 import java.util.Iterator; | |
10 | 22 import java.util.LinkedList; |
8 | 23 |
18 | 24 import javax.imageio.ImageIO; |
25 | |
45 | 26 import myVncClient.MulticastQueue.Client; |
27 | |
25 | 28 import java.util.concurrent.ExecutorService; |
69 | 29 import java.util.concurrent.atomic.AtomicBoolean; |
30 import java.util.concurrent.atomic.AtomicInteger; | |
60 | 31 import java.util.zip.DataFormatException; |
32 import java.util.zip.Deflater; | |
33 import java.util.zip.Inflater; | |
25 | 34 import java.io.OutputStream; |
7 | 35 |
60 | 36 public |
69 | 37 class MyRfbProto extends RfbProto { |
27 | 38 final static String versionMsg_3_998 = "RFB 003.998\n"; |
60 | 39 /** |
40 * CheckMillis is one of new msgType for RFB 3.998. | |
41 */ | |
42 final static byte SpeedCheckMillis = 4; | |
43 private static final int INFLATE_BUFSIZE = 1024*100; | |
44 boolean printStatusFlag = false; | |
45 long startCheckTime; | |
45 | 46 |
15 | 47 private int messageType; |
48 private int rectangles; | |
19 | 49 private int rectX; |
50 private int rectY; | |
51 private int rectW; | |
52 private int rectH; | |
15 | 53 private int encoding; |
19 | 54 private int zLen; |
69 | 55 private boolean clicomp = false; |
15 | 56 |
19 | 57 private ServerSocket servSock; |
18 | 58 private int acceptPort; |
8 | 59 private byte initData[]; |
45 | 60 private LinkedList<Socket> cliListTmp; |
61 private LinkedList<Socket> cliList; | |
19 | 62 boolean createBimgFlag; |
72 | 63 //override |
64 InterfaceForViewer viewer; | |
34 | 65 |
25 | 66 ExecutorService executor; |
45 | 67 |
18 | 68 byte[] pngBytes; |
45 | 69 |
60 | 70 // private MulticastQueue<LinkedList<ByteBuffer>> multicastqueue = new MostRecentMultiCast<LinkedList<ByteBuffer>>(10); |
71 private MulticastQueue<LinkedList<ByteBuffer>> multicastqueue = new MulticastQueue<LinkedList<ByteBuffer>>(); | |
72 private int clients = 0; | |
73 private Inflater inflater = new Inflater(); | |
69 | 74 private Deflater deflater = new Deflater(); |
45 | 75 |
69 | 76 public |
77 MyRfbProto() throws IOException { | |
78 } | |
79 | |
45 | 80 MyRfbProto(String h, int p, VncViewer v) throws IOException { |
7 | 81 super(h, p, v); |
45 | 82 cliList = new LinkedList<Socket>(); |
83 cliListTmp = new LinkedList<Socket>(); | |
19 | 84 createBimgFlag = false; |
45 | 85 // sendThreads = new LinkedList<Thread>(); |
86 // executor = Executors.newCachedThreadPool(); | |
87 // executor = Executors.newSingleThreadExecutor(); | |
10 | 88 } |
72 | 89 |
15 | 90 MyRfbProto(String h, int p) throws IOException { |
91 super(h, p); | |
45 | 92 cliList = new LinkedList<Socket>(); |
93 cliListTmp = new LinkedList<Socket>(); | |
19 | 94 createBimgFlag = false; |
45 | 95 // sendThreads = new LinkedList<Thread>(); |
96 // executor = Executors.newCachedThreadPool(); | |
97 // executor = Executors.newSingleThreadExecutor(); | |
15 | 98 } |
72 | 99 |
100 | |
101 void readVersionMsg() throws Exception { | |
102 | |
103 byte[] b = new byte[12]; | |
104 | |
105 readFully(b); | |
106 | |
107 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ') | |
108 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9') | |
109 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.') | |
110 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9') | |
111 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n')) { | |
112 throw new Exception("Host " + host + " port " + port | |
113 + " is not an RFB server"); | |
114 } | |
115 | |
116 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0'); | |
117 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0'); | |
118 | |
119 if (serverMajor < 3) { | |
120 throw new Exception( | |
121 "RFB server does not support protocol version 3"); | |
122 } | |
123 | |
124 if (serverMinor == 998) { | |
125 | |
126 } | |
127 | |
128 } | |
73 | 129 byte[] readEchoPort() throws Exception { |
130 byte[] b = new byte[4]; | |
131 readFully(b); | |
132 | |
133 return b; | |
134 } | |
135 | |
136 | |
72 | 137 |
69 | 138 void changeParent(String h, int p) throws IOException { |
139 host = h; | |
140 port = p; | |
84 | 141 |
69 | 142 sock = new Socket(host, port); |
143 is = new DataInputStream(new BufferedInputStream(sock.getInputStream(), | |
144 16384)); | |
145 os = sock.getOutputStream(); | |
146 | |
147 timing = false; | |
148 timeWaitedIn100us = 5; | |
149 timedKbits = 0; | |
150 } | |
151 | |
28 | 152 // over write |
27 | 153 void writeVersionMsg() throws IOException { |
154 clientMajor = 3; | |
99 | 155 if (serverMinor >= 9) { |
156 clientMinor = 9; | |
157 os.write(versionMsg_3_998.getBytes()); | |
27 | 158 } else if (serverMajor > 3 || serverMinor >= 8) { |
159 clientMinor = 8; | |
160 os.write(versionMsg_3_8.getBytes()); | |
161 } else if (serverMinor >= 7) { | |
162 clientMinor = 7; | |
163 os.write(versionMsg_3_7.getBytes()); | |
164 } else { | |
165 clientMinor = 3; | |
166 os.write(versionMsg_3_3.getBytes()); | |
167 } | |
168 protocolTightVNC = false; | |
169 initCapabilities(); | |
170 } | |
171 | |
45 | 172 void initServSock(int port) throws IOException { |
10 | 173 servSock = new ServerSocket(port); |
18 | 174 acceptPort = port; |
175 } | |
45 | 176 |
69 | 177 // 5550を開けるが、開いてないなら+1のポートを開ける。 |
60 | 178 void selectPort(int p) { |
179 int port = p; | |
45 | 180 while (true) { |
181 try { | |
60 | 182 initServSock(port); |
18 | 183 break; |
45 | 184 } catch (BindException e) { |
60 | 185 port++; |
18 | 186 continue; |
45 | 187 } catch (IOException e) { |
19 | 188 |
18 | 189 } |
190 } | |
60 | 191 System.out.println("accept port = " + port); |
18 | 192 } |
45 | 193 |
194 int getAcceptPort() { | |
18 | 195 return acceptPort; |
7 | 196 } |
45 | 197 |
10 | 198 void setSoTimeout(int num) throws IOException { |
199 servSock.setSoTimeout(num); | |
200 } | |
45 | 201 |
10 | 202 Socket accept() throws IOException { |
203 return servSock.accept(); | |
204 } | |
205 | |
45 | 206 void addSock(Socket sock) { |
10 | 207 cliList.add(sock); |
208 } | |
45 | 209 |
210 void addSockTmp(Socket sock) { | |
211 System.out.println("connected " + sock.getInetAddress()); | |
19 | 212 cliListTmp.add(sock); |
213 } | |
45 | 214 |
8 | 215 boolean markSupported() { |
7 | 216 return is.markSupported(); |
217 } | |
45 | 218 |
8 | 219 void readServerInit() throws IOException { |
45 | 220 |
60 | 221 is.mark(255); |
8 | 222 skipBytes(20); |
223 int nlen = readU32(); | |
45 | 224 int blen = 20 + 4 + nlen; |
10 | 225 initData = new byte[blen]; |
60 | 226 is.reset(); |
10 | 227 |
60 | 228 is.mark(blen); |
8 | 229 readFully(initData); |
60 | 230 is.reset(); |
45 | 231 |
7 | 232 framebufferWidth = readU16(); |
233 framebufferHeight = readU16(); | |
234 bitsPerPixel = readU8(); | |
235 depth = readU8(); | |
236 bigEndian = (readU8() != 0); | |
237 trueColour = (readU8() != 0); | |
238 redMax = readU16(); | |
239 greenMax = readU16(); | |
240 blueMax = readU16(); | |
241 redShift = readU8(); | |
242 greenShift = readU8(); | |
243 blueShift = readU8(); | |
8 | 244 byte[] pad = new byte[3]; |
245 readFully(pad); | |
246 int nameLength = readU32(); | |
247 byte[] name = new byte[nameLength]; | |
248 readFully(name); | |
249 desktopName = new String(name); | |
7 | 250 |
8 | 251 // Read interaction capabilities (TightVNC protocol extensions) |
252 if (protocolTightVNC) { | |
253 int nServerMessageTypes = readU16(); | |
254 int nClientMessageTypes = readU16(); | |
255 int nEncodingTypes = readU16(); | |
256 readU16(); | |
257 readCapabilityList(serverMsgCaps, nServerMessageTypes); | |
258 readCapabilityList(clientMsgCaps, nClientMessageTypes); | |
259 readCapabilityList(encodingCaps, nEncodingTypes); | |
260 } | |
261 | |
262 inNormalProtocol = true; | |
7 | 263 } |
264 | |
45 | 265 void sendRfbVersion(OutputStream os) throws IOException { |
78 | 266 // os.write(versionMsg_3_998.getBytes()); |
267 os.write(versionMsg_3_8.getBytes()); | |
27 | 268 } |
45 | 269 |
28 | 270 void readVersionMsg(InputStream is) throws IOException { |
271 | |
272 byte[] b = new byte[12]; | |
273 | |
274 is.read(b); | |
275 | |
276 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ') | |
277 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9') | |
278 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.') | |
279 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9') | |
280 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n')) { | |
281 throw new IOException("Host " + host + " port " + port | |
282 + " is not an RFB server"); | |
283 } | |
284 | |
285 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0'); | |
286 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0'); | |
287 | |
288 if (serverMajor < 3) { | |
289 throw new IOException( | |
290 "RFB server does not support protocol version 3"); | |
45 | 291 } |
292 | |
73 | 293 |
45 | 294 } |
295 | |
73 | 296 |
27 | 297 void sendSecurityType(OutputStream os) throws IOException { |
298 // number-of-security-types | |
299 os.write(1); | |
45 | 300 // security-types |
27 | 301 // 1:None |
302 os.write(1); | |
303 } | |
45 | 304 |
28 | 305 void readSecType(InputStream is) throws IOException { |
306 byte[] b = new byte[1]; | |
307 is.read(b); | |
308 | |
309 } | |
45 | 310 |
28 | 311 void sendSecResult(OutputStream os) throws IOException { |
312 byte[] b = castIntByte(0); | |
313 os.write(b); | |
314 } | |
45 | 315 |
27 | 316 void readClientInit(InputStream in) throws IOException { |
317 byte[] b = new byte[0]; | |
318 in.read(b); | |
319 } | |
45 | 320 |
321 void sendInitData(OutputStream os) throws IOException { | |
322 os.write(initData); | |
8 | 323 } |
10 | 324 |
45 | 325 |
326 void sendPngImage() { | |
327 try { | |
328 for (Socket cli : cliListTmp) { | |
329 try { | |
19 | 330 sendPngData(cli); |
331 addSock(cli); | |
45 | 332 } catch (IOException e) { |
19 | 333 // if socket closed |
334 cliListTmp.remove(cli); | |
335 } | |
336 } | |
45 | 337 // System.out.println("cliSize="+cliSize()); |
338 } catch (Exception e) { | |
19 | 339 } |
340 cliListTmp.clear(); | |
341 } | |
342 | |
15 | 343 boolean ready() throws IOException { |
344 BufferedReader br = new BufferedReader(new InputStreamReader(is)); | |
345 return br.ready(); | |
45 | 346 } |
10 | 347 |
45 | 348 int cliSize() { |
10 | 349 return cliList.size(); |
45 | 350 } |
351 | |
352 void printNumBytesRead() { | |
353 System.out.println("numBytesRead=" + numBytesRead); | |
354 } | |
355 | |
44
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
356 |
45 | 357 |
358 void regiFramebufferUpdate() throws IOException { | |
60 | 359 is.mark(20); |
360 messageType = readU8(); // 0 | |
361 skipBytes(1); // 1 | |
362 rectangles = readU16(); // 2 | |
363 rectX = readU16(); // 4 | |
364 rectY = readU16(); // 6 | |
365 rectW = readU16(); // 8 | |
366 rectH = readU16(); // 10 | |
367 encoding = readU32(); // 12 | |
78 | 368 // System.out.println("encoding = "+encoding); |
69 | 369 if (encoding == EncodingZRLE|| encoding==EncodingZRLEE||encoding==EncodingZlib) |
44
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
370 zLen = readU32(); |
60 | 371 else |
372 zLen = 0; | |
373 is.reset(); | |
69 | 374 |
60 | 375 } |
376 | |
377 int checkAndMark() throws IOException { | |
378 int dataLen; | |
379 switch (encoding) { | |
380 case RfbProto.EncodingRaw: | |
381 dataLen = rectW * rectH * 4 + 16; | |
382 is.mark(dataLen); | |
383 break; | |
384 case RfbProto.EncodingCopyRect: | |
385 dataLen = 16 + 4; | |
386 is.mark(dataLen); | |
387 break; | |
388 case RfbProto.EncodingRRE: | |
389 case RfbProto.EncodingCoRRE: | |
390 case RfbProto.EncodingHextile: | |
391 case RfbProto.EncodingTight: | |
392 dataLen = zLen + 20; | |
393 is.mark(dataLen); | |
394 break; | |
395 case RfbProto.EncodingZlib: | |
396 case RfbProto.EncodingZRLE: | |
69 | 397 case RfbProto.EncodingZRLEE: |
60 | 398 dataLen = zLen + 20; |
399 is.mark(dataLen); | |
400 break; | |
401 case RfbProto.EncodingXCursor: | |
402 case RfbProto.EncodingRichCursor: | |
403 int pixArray = rectW * rectH * 4; | |
404 int u8Array = (int)Math.floor((rectW + 7)/8) * rectH; | |
405 dataLen = pixArray + u8Array; | |
406 printFramebufferUpdate(); | |
407 is.mark(dataLen); | |
408 break; | |
409 default: | |
410 dataLen = 1000000; | |
411 is.mark(dataLen); | |
412 } | |
44
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
413 return dataLen; |
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
414 } |
60 | 415 |
45 | 416 |
60 | 417 void sendDataToClient() throws Exception { |
44
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
418 regiFramebufferUpdate(); |
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
419 int dataLen = checkAndMark(); |
034528dfb650
modify MuRfbProto.java VncCanvas.java. create sendDataToClient method.
e085711
parents:
34
diff
changeset
|
420 readSendData(dataLen); |
25 | 421 } |
45 | 422 |
423 BufferedImage createBufferedImage(Image img) { | |
424 BufferedImage bimg = new BufferedImage(img.getWidth(null), | |
425 img.getHeight(null), BufferedImage.TYPE_INT_RGB); | |
19 | 426 |
427 Graphics g = bimg.getGraphics(); | |
428 g.drawImage(img, 0, 0, null); | |
429 g.dispose(); | |
430 return bimg; | |
431 } | |
432 | |
45 | 433 void createPngBytes(BufferedImage bimg) throws IOException { |
434 pngBytes = getImageBytes(bimg, "png"); | |
19 | 435 } |
45 | 436 |
437 byte[] getBytes(BufferedImage img) throws IOException { | |
19 | 438 byte[] b = getImageBytes(img, "png"); |
439 return b; | |
15 | 440 } |
45 | 441 |
442 byte[] getImageBytes(BufferedImage image, String imageFormat) | |
443 throws IOException { | |
19 | 444 ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
445 BufferedOutputStream os = new BufferedOutputStream(bos); | |
446 image.flush(); | |
447 ImageIO.write(image, imageFormat, os); | |
448 os.flush(); | |
449 os.close(); | |
450 return bos.toByteArray(); | |
451 } | |
452 | |
45 | 453 void sendPngData(Socket sock) throws IOException { |
19 | 454 byte[] dataLength = castIntByte(pngBytes.length); |
455 sock.getOutputStream().write(dataLength); | |
456 sock.getOutputStream().write(pngBytes); | |
457 } | |
45 | 458 |
459 byte[] castIntByte(int len) { | |
19 | 460 byte[] b = new byte[4]; |
45 | 461 b[0] = (byte) ((len >>> 24) & 0xFF); |
462 b[1] = (byte) ((len >>> 16) & 0xFF); | |
463 b[2] = (byte) ((len >>> 8) & 0xFF); | |
464 b[3] = (byte) ((len >>> 0) & 0xFF); | |
19 | 465 return b; |
466 } | |
45 | 467 |
468 BufferedImage createBimg() throws IOException { | |
19 | 469 BufferedImage bimg = ImageIO.read(new ByteArrayInputStream(pngBytes)); |
470 return bimg; | |
471 } | |
69 | 472 |
45 | 473 void printFramebufferUpdate() { |
474 | |
15 | 475 System.out.println("messageType=" + messageType); |
45 | 476 System.out.println("rectangles=" + rectangles); |
15 | 477 System.out.println("encoding=" + encoding); |
60 | 478 System.out.println("rectX = "+rectX+": rectY = "+rectY); |
479 System.out.println("rectW = "+rectW+": rectH = "+rectH); | |
45 | 480 switch (encoding) { |
19 | 481 case RfbProto.EncodingRaw: |
45 | 482 System.out.println("rectW * rectH * 4 + 16 =" + rectW * rectH * 4 |
483 + 16); | |
19 | 484 break; |
485 default: | |
486 } | |
15 | 487 } |
60 | 488 |
489 void readSpeedCheck() throws IOException { | |
490 byte[] b = new byte[1]; | |
491 readFully(b); | |
492 } | |
493 | |
494 void startSpeedCheck() { | |
495 ByteBuffer b = ByteBuffer.allocate(10); | |
496 b.put((byte)SpeedCheckMillis); | |
497 b.flip(); | |
498 startCheckTime = System.currentTimeMillis(); | |
499 System.out.println("startChckTime = "+ startCheckTime); | |
500 LinkedList<ByteBuffer>bufs = new LinkedList<ByteBuffer>(); | |
501 bufs.add(b); | |
502 multicastqueue.put(bufs); | |
503 } | |
504 | |
505 void endSpeedCheck() { | |
506 long accTime = System.currentTimeMillis(); | |
507 long time = accTime - startCheckTime; | |
508 System.out.println("checkMillis: " + time); | |
509 } | |
510 | |
511 | |
512 synchronized void changeStatusFlag() { | |
513 printStatusFlag = true; | |
514 } | |
515 | |
516 void printMills() { | |
517 if(printStatusFlag) { | |
518 | |
519 changeStatusFlag(); | |
520 } else { | |
521 changeStatusFlag(); | |
522 } | |
523 } | |
524 | |
525 void speedCheckMillis() { | |
526 Runnable stdin = new Runnable() { | |
527 public void run() { | |
528 int c; | |
529 try { | |
530 while( (c = System.in.read()) != -1 ) { | |
531 switch(c) { | |
532 case 's': | |
533 break; | |
534 default: | |
535 startSpeedCheck(); | |
536 break; | |
537 } | |
538 } | |
539 }catch(IOException e){ | |
540 System.out.println(e); | |
541 } | |
542 } | |
543 }; | |
544 | |
545 new Thread(stdin).start(); | |
546 } | |
547 | |
548 /** | |
549 * gzip byte arrays | |
550 * @param deflater | |
551 * @param inputs | |
552 * byte data[] | |
553 * @param inputIndex | |
554 * @param outputs | |
555 * byte data[] | |
556 * @return byte length in last byte array | |
557 * @throws IOException | |
558 */ | |
559 public int zip(Deflater deflater,LinkedList<ByteBuffer> inputs, int inputIndex, LinkedList<ByteBuffer> outputs) throws IOException { | |
560 int len = 0; | |
561 ByteBuffer c1= ByteBuffer.allocate(INFLATE_BUFSIZE); | |
562 while(inputIndex < inputs.size() ) { | |
563 ByteBuffer b1 = inputs.get(inputIndex++); | |
564 deflater.setInput(b1.array(),b1.position(),b1.remaining()); | |
69 | 565 /** |
566 * If we finish() stream and reset() it, Deflater start new gzip stream, this makes continuous zlib reader unhappy. | |
567 * if we remove finish(), Deflater.deflate() never flushes its output. The original zlib deflate has flush flag. I'm pretty | |
568 * sure this a kind of bug of Java library. | |
569 */ | |
570 if (inputIndex==inputs.size()) | |
571 deflater.finish(); | |
572 int len1 = 0; | |
60 | 573 do { |
69 | 574 len1 = deflater.deflate(c1.array(),c1.position(),c1.remaining()); |
60 | 575 if (len1>0) { |
576 len += len1; | |
577 c1.position(c1.position()+len1); | |
578 if (c1.remaining()==0) { | |
579 c1.flip(); outputs.addLast(c1); | |
580 c1 = ByteBuffer.allocate(INFLATE_BUFSIZE); | |
581 } | |
582 } | |
69 | 583 } while (len1 >0 || !deflater.needsInput()); // &&!deflater.finished()); |
60 | 584 } |
585 if (c1.position()!=0) { | |
586 c1.flip(); outputs.addLast(c1); | |
587 } | |
588 deflater.reset(); | |
589 return len; | |
590 } | |
591 | |
592 /** | |
593 * gunzip byte arrays | |
594 * @param inflater | |
595 * @param inputs | |
596 * byte data[] | |
597 * @param outputs | |
598 * byte data[] | |
599 *@return number of total bytes | |
600 * @throws IOException | |
601 */ | |
69 | 602 public int unzip(Inflater inflater, LinkedList<ByteBuffer> inputs, int inputIndex, LinkedList<ByteBuffer> outputs,int bufSize) |
60 | 603 throws DataFormatException { |
604 int len=0; | |
69 | 605 ByteBuffer buf = ByteBuffer.allocate(bufSize); |
60 | 606 while (inputIndex < inputs.size()) { |
607 ByteBuffer input = inputs.get(inputIndex++); | |
608 inflater.setInput(input.array(),input.position(),input.limit()); | |
69 | 609 // if (inputIndex==inputs.size()) if inflater/deflater has symmetry, we need this |
610 // inflater.end(); but this won't work | |
60 | 611 do { |
612 int len0 = inflater.inflate(buf.array(),buf.position(),buf.remaining()); | |
613 if (len0>0) { | |
614 buf.position(buf.position()+len0); | |
615 len += len0; | |
616 if (buf.remaining()==0) { | |
617 buf.flip(); | |
618 outputs.addLast(buf); | |
69 | 619 buf = ByteBuffer.allocate(bufSize); |
60 | 620 } |
621 } | |
622 } while (!inflater.needsInput()); | |
623 } | |
624 if (buf.position()!=0) { | |
625 buf.flip(); | |
626 outputs.addLast(buf); | |
627 } | |
628 return len; | |
629 } | |
630 | |
69 | 631 /** |
632 * send data to clients | |
633 * @param dataLen | |
634 * @throws IOException | |
635 * @throws DataFormatException | |
636 * | |
637 * Zlibed packet is compressed in context dependent way, that is, it have to send from the beginning. But this is | |
638 * impossible. So we have to compress it again for each clients. Separate deflater for each clients is necessary. | |
639 * | |
640 * Java's deflater does not support flush. This means to get the result, we have to finish the compression. Reseting | |
641 * start new compression, but it is not accepted well in zlib continuous reading. So we need new Encoding ZRLEE | |
642 * which reset decoder for each packet. ZRLEE can be invisible from user, but it have to be implemented in the clients. | |
643 * ZRLEE compression is not context dependent, so no recompression is necessary. | |
644 */ | |
60 | 645 void readSendData(int dataLen) throws IOException, DataFormatException { |
646 LinkedList<ByteBuffer>bufs = new LinkedList<ByteBuffer>(); | |
647 ByteBuffer header = ByteBuffer.allocate(16); | |
648 readFully(header.array(),0,16); | |
649 header.limit(16); | |
650 if (header.get(0)==RfbProto.FramebufferUpdate) { | |
651 int encoding = header.getInt(12); | |
69 | 652 if (encoding==RfbProto.EncodingZRLE||encoding==RfbProto.EncodingZlib) { // ZRLEE is already recompressed |
60 | 653 ByteBuffer len = ByteBuffer.allocate(4); |
654 readFully(len.array(),0,4); len.limit(4); | |
655 ByteBuffer inputData = ByteBuffer.allocate(dataLen-20); | |
656 readFully(inputData.array(),0,inputData.capacity()); inputData.limit(dataLen-20); | |
657 LinkedList<ByteBuffer>inputs = new LinkedList<ByteBuffer>(); | |
658 inputs.add(inputData); | |
69 | 659 |
660 header.putInt(12, RfbProto.EncodingZRLEE); // means recompress every time | |
661 // using new Deflecter every time is incompatible with the protocol, clients have to be modified. | |
662 Deflater nDeflater = deflater; // new Deflater(); | |
663 LinkedList<ByteBuffer> out = new LinkedList<ByteBuffer>(); | |
664 unzip(inflater, inputs, 0 , out, INFLATE_BUFSIZE); | |
665 // dump32(inputs); | |
666 int len2 = zip(nDeflater, out, 0, bufs); | |
667 ByteBuffer blen = ByteBuffer.allocate(4); blen.putInt(len2); blen.flip(); | |
668 bufs.addFirst(blen); | |
669 | |
60 | 670 bufs.addFirst(header); |
671 multicastqueue.put(bufs); | |
672 is.reset(); | |
673 return ; | |
674 } | |
675 } | |
676 bufs.add(header); | |
677 if (dataLen>16) { | |
678 ByteBuffer b = ByteBuffer.allocate(dataLen-16); | |
679 readFully(b.array(),0,dataLen-16); b.limit(dataLen-16); | |
680 bufs.add(b); | |
681 } | |
682 multicastqueue.put(bufs); | |
683 is.reset(); | |
684 | |
685 // It may be compressed. We can inflate here to avoid repeating clients decompressing here, | |
686 // but it may generate too many large data. It is better to do it in each client. | |
687 // But we have do inflation for all input data, so we have to do it here. | |
688 } | |
45 | 689 |
54 | 690 void newClient(AcceptThread acceptThread, final Socket newCli, |
45 | 691 final OutputStream os, final InputStream is) throws IOException { |
692 // createBimgFlag = true; | |
693 // rfb.addSockTmp(newCli); | |
694 // addSock(newCli); | |
69 | 695 final int myId = clients; |
60 | 696 final Client <LinkedList<ByteBuffer>> c = multicastqueue.newClient(); |
69 | 697 final AtomicInteger writerRunning = new AtomicInteger(); |
698 writerRunning.set(1); | |
699 /** | |
700 * Timeout thread. If a client is suspended, it has top of queue indefinitely, which caused memory | |
701 * overflow. After the timeout, we poll the queue and discard it. Start long wait if writer is running. | |
702 */ | |
703 final Runnable timer = new Runnable() { | |
704 public void run() { | |
705 int count = 0; | |
706 for(;;) { | |
707 long timeout = 30000/8; | |
708 try { | |
709 synchronized(this) { | |
710 int state,flag; | |
711 writerRunning.set(0); | |
712 wait(timeout); | |
713 flag = 0; | |
714 while((state=writerRunning.get())==0) { | |
715 c.poll(); // discard, should be timeout | |
716 count++; | |
717 if (flag==0) { | |
718 System.out.println("Discarding "+myId + " count="+ count); flag = 1; | |
719 } | |
720 wait(10); // if this is too short, writer cannot take the poll, if this is too long, memory will overflow... | |
721 } | |
722 if (flag==1) System.out.println("Resuming "+myId + " count="+count); | |
723 if (state!=1) { | |
724 System.out.println("Client died "+myId); | |
725 break; | |
726 } | |
727 } | |
728 } catch (InterruptedException e) { | |
729 } | |
730 } | |
731 } | |
732 }; | |
733 new Thread(timer).start(); | |
734 /** | |
735 * discard all incoming from clients | |
736 */ | |
60 | 737 final Runnable reader = new Runnable() { |
45 | 738 public void run() { |
60 | 739 byte b[] = new byte[4096]; |
740 for(;;) { | |
741 try { | |
742 int c = is.read(b); | |
743 if (c<=0) throw new IOException(); | |
69 | 744 // System.out.println("client read "+c); |
60 | 745 } catch (IOException e) { |
746 try { | |
69 | 747 writerRunning.set(2); |
60 | 748 os.close(); |
749 is.close(); | |
750 } catch (IOException e1) { | |
751 } | |
752 return; | |
753 } | |
754 } | |
755 } | |
756 }; | |
69 | 757 /** |
758 * send packets to a client | |
759 */ | |
60 | 760 Runnable sender = new Runnable() { |
761 public void run() { | |
69 | 762 writerRunning.set(1); |
45 | 763 try { |
60 | 764 /** |
765 * initial connection of RFB protocol | |
766 */ | |
45 | 767 sendRfbVersion(os); |
768 readVersionMsg(is); | |
769 sendSecurityType(os); | |
770 readSecType(is); | |
771 sendSecResult(os); | |
772 readClientInit(is); | |
773 sendInitData(os); | |
69 | 774 new Thread(reader).start(); // discard incoming packet here after. |
45 | 775 for (;;) { |
60 | 776 LinkedList<ByteBuffer> bufs = c.poll(); |
777 int inputIndex = 0; | |
69 | 778 ByteBuffer header = bufs.get(inputIndex); |
60 | 779 if (header==null) continue; |
780 if (header.get(0)==RfbProto.FramebufferUpdate) { | |
69 | 781 // System.out.println("client "+ myId); |
60 | 782 } |
69 | 783 writeToClient(os, bufs, inputIndex); |
784 writerRunning.set(1); // yes my client is awaking. | |
45 | 785 } |
786 } catch (IOException e) { | |
60 | 787 try { |
69 | 788 writerRunning.set(2); |
60 | 789 os.close(); |
790 } catch (IOException e1) { | |
81 | 791 /* if socket closed cliList.remove(newCli); */ |
60 | 792 } |
45 | 793 } |
794 } | |
69 | 795 |
796 public void writeToClient(final OutputStream os, | |
797 LinkedList<ByteBuffer> bufs, int inputIndex) | |
798 throws IOException { | |
799 while(inputIndex < bufs.size()) { | |
800 ByteBuffer b = bufs.get(inputIndex++); | |
801 os.write(b.array(), b.position(), b.limit()); | |
802 } | |
803 os.flush(); | |
804 } | |
45 | 805 }; |
60 | 806 clients++; |
45 | 807 new Thread(sender).start(); |
808 | |
809 } | |
60 | 810 |
69 | 811 |
812 public void dump32(LinkedList<ByteBuffer>bufs) { | |
813 int len =0; | |
814 for(ByteBuffer b: bufs) len += b.remaining(); | |
815 ByteBuffer top = bufs.getFirst(); | |
816 ByteBuffer end = bufs.getLast(); | |
817 System.err.println("length: "+len); | |
818 System.err.print("head 0: "); | |
819 for(int i = 0; i<16 && i < top.remaining(); i++) { | |
820 System.err.print(" "+ top.get(i)); | |
821 } | |
822 System.err.print("tail 0: "); | |
823 for(int i = 0; i<16 && i < end.remaining(); i++) { | |
824 System.err.print(" "+end.get(i)); | |
825 } | |
826 System.err.println(); | |
827 } | |
828 | |
829 private Iterable<Byte> byteBufferIterator(final LinkedList<ByteBuffer> in) { | |
830 return new Iterable<Byte>() { | |
831 public Iterator<Byte> iterator() { | |
832 return new Iterator<Byte>() { | |
833 int bytes = 0; | |
834 int buffers = 0; | |
835 public boolean hasNext() { | |
836 for(;;) { | |
837 if (buffers>=in.size()) return false; | |
838 ByteBuffer b = in.get(buffers); | |
839 if (! (bytes<b.remaining())) { | |
840 buffers ++; bytes=0; | |
841 } else return true; | |
842 } | |
843 } | |
844 public Byte next() { | |
845 ByteBuffer bf =in.get(buffers); | |
846 byte b = bf.get(bytes++); | |
847 if (bf.remaining()<=bytes) { | |
848 buffers++; | |
849 bytes = 0; | |
850 } | |
851 // System.out.print(b); | |
852 return b; | |
853 } | |
854 public void remove() { | |
855 } | |
856 }; | |
857 } | |
858 }; | |
859 } | |
860 | |
45 | 861 } |
60 | 862 |
863 |