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