github
net-reactor
It’s a simple and easy NET Framework with Nio Mode written by Java
reactor model
how-to
just simply like:
public class MyHandler implements Handler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);
private long readSize;
/**
* The logic to deal with the received data.
*
* It means that reactor will trigger this function once the data is received.
* @throws IOException
*/
public void handle(FrontendConnection connection) throws IOException {
Buffer buff = connection.getReadBuffer();
readSize = +readSize + buff.position();
LOGGER.info(connection.getId() + " connection has receive "+ readSize); }}Copy the code
Handler handler = new MyHandler();
ReactorPool reactorPool = new ReactorPool(Runtime.getRuntime().availableProcessors(), handler);
new Acceptor(reactorPool, acceptorName, host, port).start(a);Copy the code
adding a connection event or a connection multi-event:
public class RegisterHandler implements ConnectionEventHandler {
private static final Logger LOGGER = LoggerFactory
.getLogger(RegisterHandler.class);
private static int INTERESTED = ConnectionEvents.REGISTE;
public void event(FrontendConnection connection) {
if((event & INTERESTED) ! =0) {
//do something here }}}Copy the code
Handler handler = new NetHandler();
ConnectionEventHandler connectionEventHandler = new RegisterHandler();
ReactorPool reactorPool = new ReactorPool(Runtime.getRuntime().availableProcessors(), handler);
Acceptor acceptor = new Acceptor(reactorPool, acceptorName, host, port);
acceptor.addConnectionEventHandler(connectionEventHandler);
acceptor.start(a);Copy the code
public class ConnectionLogHandler implements ConnectionEventHandler {
private static final Logger LOGGER = LoggerFactory
.getLogger(ConnectionLogHandler.class);
private static int INTERESTED = ConnectionEvents.ACCEPT
| ConnectionEvents.CLOSE;
public void event(Connection connection, int event) {
if((event & INTERESTED) ! =0) {
if((event & ConnectionEvents.ACCEPT) ! =0)
LOGGER.info("accept connection,id is " + connection.getId());
if((event & ConnectionEvents.CLOSE) ! =0)
LOGGER.info("close connection,id is "+ connection.getId()); }}}Copy the code
implements the connection
public class XXXConnection extends Connection {
private String name;
public XXXConnection(SocketChannel channel, long id, Reactor reactor) {
super(channel, id, reactor);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; }}Copy the code
public class XXXConnectionFactory implements ConnectionFactory {
public XXXConnection createConnection(SocketChannel channel, long id,
Reactor reactor) {
return newXXXConnection(channel, id, reactor); }}Copy the code
Acceptor acceptor = new Acceptor(reactorPool, acceptorName, host,port);
acceptor.setConnectionFactory(new xxxConnectionFactory());Copy the code