public void tearDown() {
}
@Test
public void testFiberAsyncSocket() throws Exception {
final Fiber server = new Fiber(scheduler, new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution {
try (FiberServerSocketChannel socket = FiberServerSocketChannel.open().bind(new InetSocketAddress(PORT));
FiberSocketChannel ch = socket.accept()) {
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
// long-typed reqeust/response
int n = ch.read(buf);
assertThat(n, is(8)); // we assume the message is sent in a single packet
buf.flip();
long req = buf.getLong();
assertThat(req, is(12345678L));
buf.clear();
long res = 87654321L;
buf.putLong(res);
buf.flip();
n = ch.write(buf);
assertThat(n, is(8));
// String reqeust/response
buf.clear();
n = ch.read(buf); // we assume the message is sent in a single packet
buf.flip();
String req2 = decoder.decode(buf).toString();
assertThat(req2, is("my request"));
String res2 = "my response";
n = ch.write(encoder.encode(CharBuffer.wrap(res2)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
final Fiber client = new Fiber(scheduler, new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution {
try (FiberSocketChannel ch = FiberSocketChannel.open(new InetSocketAddress(PORT))) {
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
// long-typed reqeust/response
long req = 12345678L;
buf.putLong(req);
buf.flip();
int n = ch.write(buf);
assertThat(n, is(8));
buf.clear();
n = ch.read(buf);
assertThat(n, is(8)); // we assume the message is sent in a single packet
buf.flip();
long res = buf.getLong();
assertThat(res, is(87654321L));
// String reqeust/response
String req2 = "my request";
n = ch.write(encoder.encode(CharBuffer.wrap(req2)));
buf.clear();
n = ch.read(buf); // we assume the message is sent in a single packet
buf.flip();
String res2 = decoder.decode(buf).toString();
assertThat(res2, is("my response"));
// verify that the server has closed the socket
buf.clear();
n = ch.read(buf);
assertThat(n, is(-1));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
server.start();
Thread.sleep(100);
client.start();
client.join();
server.join();
}