在玩了一会儿之后,看起来这可以使用ReadableRepresentation。我不知道是否有比使用管道更好的方法来创建 ReadableByteChannel,但这是我看到的唯一方法,而不必实现我自己的 Channel。
private static final byte[] HELLO_WORLD = "hello world\n".getBytes(Charsets.UTF_8);
public static class HelloWorldResource extends ServerResource {
@Get
public Representation represent() throws Exception {
final Pipe pipe = Pipe.open();
// this simulates another process generating the data
Thread t = new Thread(new Runnable() {
private final ByteBuffer buf = ByteBuffer.allocate(1);
private final Pipe.SinkChannel sink = pipe.sink();
private int offset = 0;
@Override
public void run() {
while (offset < HELLO_WORLD.length) {
try {
buf.clear();
buf.put(HELLO_WORLD[offset++]);
buf.flip();
while (buf.hasRemaining()) {
sink.write(buf);
}
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
sink.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
return new ReadableRepresentation(pipe.source(), MediaType.TEXT_PLAIN);
}
}
public static class HelloWorldApplication extends Application {
@Override
public synchronized Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/hello", HelloWorldResource.class);
return router;
}
}
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getDefaultHost().attach("", new HelloWorldApplication());
Server server = component.getServers().add(Protocol.HTTP, 8090);
component.start();
}