View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2024 Christian Kohlschütter
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
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   * A simple bidirectional Unix socket client that reads from/writes to stdin/stdout.
29   */
30  @SuppressWarnings("CatchAndPrintStackTrace" /* errorprone */)
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  }