1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.client;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InterruptedIOException;
23 import java.io.OutputStream;
24 import java.net.Socket;
25 import java.util.concurrent.CountDownLatch;
26
27
28
29
30 @SuppressWarnings("CatchAndPrintStackTrace" )
31 public final class ReadWriteClient extends DemoClientBase {
32 @Override
33 protected void handleSocket(Socket socket) throws IOException {
34 try (InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream()) {
35 final byte[] readBuf = new byte[socket.getReceiveBufferSize()];
36 final byte[] writeBuf = new byte[socket.getSendBufferSize()];
37
38 final CountDownLatch cdl = new CountDownLatch(2);
39
40 new Thread() {
41 @Override
42 public void run() {
43 int bytes;
44 try {
45 while ((bytes = in.read(readBuf)) != -1) {
46 System.out.write(readBuf, 0, bytes);
47 System.out.flush();
48 }
49 } catch (IOException e) {
50 e.printStackTrace();
51 }
52 cdl.countDown();
53 }
54 }.start();
55
56 new Thread() {
57 @Override
58 public void run() {
59 int bytes;
60 try {
61 while ((bytes = System.in.read(writeBuf)) != -1) {
62 out.write(writeBuf, 0, bytes);
63 out.flush();
64 }
65 } catch (IOException e) {
66 e.printStackTrace();
67 }
68 cdl.countDown();
69 }
70 }.start();
71
72 cdl.await();
73 } catch (InterruptedException e) {
74 throw (InterruptedIOException) new InterruptedIOException().initCause(e);
75 }
76 }
77 }