I wrote this awhile back and make improvements here and there, and it's what I run my server from. Any suggestions or improvements? I'm completely open to them. Source code is included.
http://www.filedropper.com/nioframework
nio_framework.zip
Download nio_framework.zip from Sendspace.com - send big files the easy way
Pretty simple to use
Code:
import java.nio.ByteBuffer;
import com.palidino.nio.NIOServer;
import com.palidino.nio.Session;
import com.palidino.nio.SessionHandler;
public class MyHandler implements SessionHandler {
private NIOServer nioServer = new NIOServer();
public MyHandler() throws Exception {
nioServer.setSessionHandler(this);
nioServer.setLogDirectory("./logs");
nioServer.setMaxTotalConnections(2000);
nioServer.setReadBufferSize(8192); // 8kb
nioServer.setWriteBufferSize(16384); // 16kb
nioServer.setMaxConnectionsPerIPAddress(3);
nioServer.setSocketIOIdleTimeout(30); // 30 seconds
nioServer.setBanLength(60); // 60 seconds
nioServer.start("0.0.0.0", 43594); // bind to all IPs on port 43594
}
public void close() {
nioServer.close();
}
@Override
public void accept(Session session) {
//session.setAttachment(SOME_OBJECT);
System.out.println("Connection received from: " + session.getRemoteAddress());
}
@Override
public void read(Session session, byte[] bytes) {
//Object o = session.getAttachment();
}
@Override
public void exception(Session session, Exception exception) {
session.close();
}
@Override
public void closed(Session session) { }
}
Writing data isn't much harder
Code:
import com.palidino.nio.WriteCompleteEvent;
import com.palidino.nio.WriteEvent;
import com.palidino.nio.Session;
WriteEvent writeEvent = session.write(bytes, 0, bytes.length);
OR
WriteEvent writeEvent = session.writeClone(bytes, 0, bytes.length);
IF you want to trigger an action when this write completes
writeEvent.setWriteCompleteEvent(new WriteCompleteEvent() {
@Override
public void complete(Session session) {
session.close();
}
});