Skip to content

Instantly share code, notes, and snippets.

@mopemope
Created December 11, 2013 01:34
Show Gist options
  • Select an option

  • Save mopemope/7903692 to your computer and use it in GitHub Desktop.

Select an option

Save mopemope/7903692 to your computer and use it in GitHub Desktop.
FiberServerSocketChannel example
package com.mycompany.fiber;
import java.io.IOException;
import java.net.InetSocketAddress;
import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.fibers.io.FiberSocketChannel;
import co.paralleluniverse.fibers.io.FiberServerSocketChannel;
import co.paralleluniverse.strands.SuspendableRunnable;
import java.nio.ByteBuffer;
public class Echo {
private static final int PORT = 5000;
private Fiber<Void> createServerFiber () {
final Fiber<Void> server;
server = new Fiber<>(new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution {
try (FiberServerSocketChannel socket = FiberServerSocketChannel.open().bind(new InetSocketAddress(PORT), 1024)
) {
System.out.println(socket.supportedOptions());
for (;;) {
final FiberSocketChannel ch = socket.accept();
new Fiber<Void>(new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution, InterruptedException {
try {
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
//System.out.println(Thread.currentThread());
int n = 0;
while ((n = ch.read(buf)) != -1) {
buf.flip();
ch.write(buf);
buf.clear();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return server;
}
public void run() throws Exception{
Fiber<Void> fiber = createServerFiber();
fiber.start();
fiber.join();
}
public static void main(String[] args) throws Exception{
System.out.println("Hello Echo");
new Echo().run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment