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 private final String id
;
25 public SocketPipeMirror(String id
) throws IOException
{
28 outPipe
= Pipe
.open();
29 in
= Channels
.newInputStream(inPipe
.source());
30 out
= Channels
.newOutputStream(outPipe
.sink());
33 public void open(SocketChannel channel
) {
34 readInThread
= new Thread(() -> {
37 ByteBuffer buffer
= ByteBuffer
.allocate(1024);
38 while (!readInThread
.isInterrupted() && channel
.isConnected()) {
39 if (channel
.read(buffer
) < 0) {
44 inPipe
.sink().write(buffer
);
47 } catch (AsynchronousCloseException e
) {
49 } catch (IOException e
) {
52 }, "JShell read " + id
);
55 writeOutThread
= new Thread(() -> {
58 ByteBuffer buffer
= ByteBuffer
.allocate(1024);
59 while (!writeOutThread
.isInterrupted() && channel
.isConnected()) {
60 if (outPipe
.source().read(buffer
) < 0) {
65 channel
.write(buffer
);
68 } catch (IOException e
) {
71 }, "JShell write " + id
);
72 writeOutThread
.start();
77 public void close() throws IOException
{
78 // TODO make it more robust
79 // readInThread.interrupt();
80 // writeOutThread.interrupt();
85 } catch (InterruptedException e
) {
89 writeOutThread
.join();
90 } catch (InterruptedException e
) {
95 public InputStream
getInputStream() {
99 public OutputStream
getOutputStream() {