Create a pip package for pipe_io_server

This commit is contained in:
Kristóf Tóth
2019-08-02 15:32:38 +02:00
parent 499ce8af76
commit c39527d99e
19 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,13 @@
public class Example {
public static void main(String[] args) {
try (PipeIO pipeio = new PipeIO("in", "out")) {
pipeio.reader.setMessageHandler(new MessageHandler(){
@Override
public void call(String msg) {
pipeio.writer.sendMessage(msg);
}
});
pipeio.reader.run();
}
}
}

View File

@ -0,0 +1,3 @@
public interface MessageHandler {
public void call(String msg);
}

View File

@ -0,0 +1,17 @@
import java.io.IOException;
public class PipeIO implements AutoCloseable {
public PipeReader reader;
public PipeWriter writer;
public PipeIO(String in_pipe_path, String out_pipe_path) {
this.reader = new PipeReader(in_pipe_path);
this.writer = new PipeWriter(out_pipe_path);
}
public void close() {
this.reader.close();
this.writer.close();
}
}

View File

@ -0,0 +1,50 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.AutoCloseable;
public class PipeReader implements AutoCloseable {
private BufferedReader pipe;
private MessageHandler messageHandler;
public PipeReader(String pipe_path) {
try {
this.pipe = new BufferedReader(new FileReader(pipe_path));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
this.messageHandler = new MessageHandler(){
@Override
public void call(String msg) {}
};
}
public void close() {
try {
this.pipe.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void setMessageHandler(MessageHandler handler) {
this.messageHandler = handler;
}
public void run() {
String msg;
while ((msg = this.recvMessage()) != null) {
this.messageHandler.call(msg);
}
}
public String recvMessage() {
try {
return this.pipe.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

View File

@ -0,0 +1,35 @@
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.AutoCloseable;
public class PipeWriter implements AutoCloseable {
private BufferedWriter pipe;
public PipeWriter(String pipe_path) {
try {
this.pipe = new BufferedWriter(new FileWriter(pipe_path));
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
public void close() {
try {
this.pipe.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void sendMessage(String msg) {
try {
this.pipe.write(msg + "\n");
this.pipe.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}