1 package org
.argeo
.cms
.jshell
;
3 import java
.io
.Closeable
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
6 import java
.io
.OutputStream
;
7 import java
.nio
.ByteBuffer
;
8 import java
.nio
.channels
.AsynchronousCloseException
;
9 import java
.nio
.channels
.Channels
;
10 import java
.nio
.channels
.Pipe
;
11 import java
.nio
.channels
.SocketChannel
;
13 class SocketPipeMirror
implements Closeable
{
14 private final Pipe inPipe
;
15 private final Pipe outPipe
;
17 private final InputStream in
;
18 private final OutputStream out
;
20 private Thread readInThread
;
21 private Thread writeOutThread
;
23 public SocketPipeMirror() throws IOException
{
25 outPipe
= Pipe
.open();
26 in
= Channels
.newInputStream(inPipe
.source());
27 out
= Channels
.newOutputStream(outPipe
.sink());
30 public void open(SocketChannel channel
) {
31 readInThread
= new Thread(() -> {
34 ByteBuffer buffer
= ByteBuffer
.allocate(1024);
35 while (!readInThread
.isInterrupted() && channel
.isConnected()) {
36 if (channel
.read(buffer
) < 0)
39 inPipe
.sink().write(buffer
);
42 } catch (AsynchronousCloseException e
) {
44 // TODO make it cleaner
45 } catch (IOException e
) {
51 writeOutThread
= new Thread(() -> {
54 ByteBuffer buffer
= ByteBuffer
.allocate(1024);
55 while (!writeOutThread
.isInterrupted() && channel
.isConnected()) {
56 if (outPipe
.source().read(buffer
) < 0)
59 channel
.write(buffer
);
62 } catch (IOException e
) {
66 writeOutThread
.start();
71 public void close() throws IOException
{
72 // TODO make it more robust
73 readInThread
.interrupt();
74 writeOutThread
.interrupt();
79 public InputStream
getInputStream() {
83 public OutputStream
getOutputStream() {