client.getProperties().put(SshClient.WINDOW_SIZE, "1024");
client.start();
ClientSession session = client.connect("smx", "localhost", port).await().getSession();
session.addPasswordIdentity("smx");
session.auth().verify();
final ChannelShell channel = session.createShellChannel();
channel.setStreaming(ClientChannel.Streaming.Async);
channel.open().verify();
final byte[] message = "0123456789\n".getBytes();
final int nbMessages = 1000;
final ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
final ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
final AtomicInteger writes = new AtomicInteger(nbMessages);
channel.getAsyncIn().write(new Buffer(message))
.addListener(new SshFutureListener<IoWriteFuture>() {
public void operationComplete(IoWriteFuture future) {
try {
if (future.isWritten()) {
if (writes.decrementAndGet() > 0) {
channel.getAsyncIn().write(new Buffer(message)).addListener(this);
} else {
channel.getAsyncIn().close(false);
}
} else {
throw new SshException("Error writing", future.getException());
}
} catch (IOException e) {
if (!channel.isClosing()) {
e.printStackTrace();
channel.close(true);
}
}
}
});
channel.getAsyncOut().read(new Buffer())
.addListener(new SshFutureListener<IoReadFuture>() {
public void operationComplete(IoReadFuture future) {
try {
future.verify();
Buffer buffer = future.getBuffer();
baosOut.write(buffer.array(), buffer.rpos(), buffer.available());
buffer.rpos(buffer.rpos() + buffer.available());
buffer.compact();
channel.getAsyncOut().read(buffer).addListener(this);
} catch (IOException e) {
if (!channel.isClosing()) {
e.printStackTrace();
channel.close(true);
}
}
}
});
channel.getAsyncErr().read(new Buffer())
.addListener(new SshFutureListener<IoReadFuture>() {
public void operationComplete(IoReadFuture future) {
try {
future.verify();
Buffer buffer = future.getBuffer();
baosErr.write(buffer.array(), buffer.rpos(), buffer.available());
buffer.rpos(buffer.rpos() + buffer.available());
buffer.compact();
channel.getAsyncErr().read(buffer).addListener(this);
} catch (IOException e) {
if (!channel.isClosing()) {
e.printStackTrace();
channel.close(true);
}
}
}
});
channel.waitFor(ClientChannel.CLOSED, 0);
assertEquals(nbMessages * message.length, baosOut.size());
}