| 1 |
/* |
| 2 |
* junixsocket |
| 3 |
* |
| 4 |
* Copyright 2009-2022 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 |
public final class ReadWriteClient extends DemoClientBase { |
| 31 |
@Override |
| 32 |
protected void handleSocket(Socket socket) throws IOException { |
| 33 |
try (InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream()) { |
| 34 |
final byte[] readBuf = new byte[socket.getReceiveBufferSize()]; |
| 35 |
final byte[] writeBuf = new byte[socket.getSendBufferSize()]; |
| 36 |
|
| 37 |
final CountDownLatch cdl = new CountDownLatch(2); |
| 38 |
|
| 39 |
new Thread() { |
| 40 |
@Override |
| 41 |
public void run() { |
| 42 |
int bytes; |
| 43 |
try { |
| 44 |
while ((bytes = in.read(readBuf)) != -1) { |
| 45 |
System.out.write(readBuf, 0, bytes); |
| 46 |
System.out.flush(); |
| 47 |
} |
| 48 |
} catch (IOException e) { |
| 49 |
e.printStackTrace(); |
| 50 |
} |
| 51 |
cdl.countDown(); |
| 52 |
} |
| 53 |
}.start(); |
| 54 |
|
| 55 |
new Thread() { |
| 56 |
@Override |
| 57 |
public void run() { |
| 58 |
int bytes; |
| 59 |
try { |
| 60 |
while ((bytes = System.in.read(writeBuf)) != -1) { |
| 61 |
out.write(writeBuf, 0, bytes); |
| 62 |
out.flush(); |
| 63 |
} |
| 64 |
} catch (IOException e) { |
| 65 |
e.printStackTrace(); |
| 66 |
} |
| 67 |
cdl.countDown(); |
| 68 |
} |
| 69 |
}.start(); |
| 70 |
|
| 71 |
cdl.await(); |
| 72 |
} catch (InterruptedException e) { |
| 73 |
throw (InterruptedIOException) new InterruptedIOException().initCause(e); |
| 74 |
} |
| 75 |
} |
| 76 |
} |