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)
42 inPipe
.sink().write(buffer
);
45 } catch (AsynchronousCloseException e
) {
47 // TODO make it cleaner
48 } catch (IOException e
) {
51 }, "JShell read " + id
);
54 writeOutThread
= new Thread(() -> {
57 ByteBuffer buffer
= ByteBuffer
.allocate(1024);
58 while (!writeOutThread
.isInterrupted() && channel
.isConnected()) {
59 if (outPipe
.source().read(buffer
) < 0)
62 channel
.write(buffer
);
65 } catch (IOException e
) {
68 }, "JShell write " + id
);
69 writeOutThread
.start();
74 public void close() throws IOException
{
75 // TODO make it more robust
76 // readInThread.interrupt();
77 // writeOutThread.interrupt();
82 } catch (InterruptedException e
) {
86 writeOutThread
.join();
87 } catch (InterruptedException e
) {
92 public InputStream
getInputStream() {
96 public OutputStream
getOutputStream() {