Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

nio and http request  RSS feed

Nicolas Viollin
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I must write an app that controls http requests. I would like to use java.nio.* API, but I don't know how to keep a trace of which connection is asking for what and forward the data back to it:

Let's say I open ask for the page, my proxy will get the incoming connection, will read the request, the will have to send it to the web site i want to access. The only thing is how fo I know who's asking for which website ???

Here is the code I use to read incoming connections:

public void run(){
while (getRun()){
int num =;

if (num == 0)

Set keys = _selector.selectedKeys();
Iterator it = keys.iterator();
while (it.hasNext()){
SelectionKey key = (SelectionKey);

if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
else if ((key.readyOps() & SelectionKey.OP_READ) ==


}catch(Exception e){

private void incomingConnection() throws Exception{
Socket s = _ss.accept();
System.out.println( "Got connection from "+s );

// Make sure to make it non-blocking, so we can
// use a selector on it.
SocketChannel sc = s.getChannel();
sc.configureBlocking( false );

// Register it with the selector, for reading
sc.register( _selector, SelectionKey.OP_READ );

private void incomingData(SelectionKey key){
SocketChannel sc = null;

try {

// It's incoming data on a connection, so
// process it
sc = (SocketChannel);
boolean ok = readData(sc);

// If the connection is dead, then remove it
// from the selector and close it
if (!ok) {

Socket s = null;
try {
s = sc.socket();
} catch( IOException ie ) {
System.err.println( "Error closing socket "+s+": "+ie );

} catch( Exception ie ) {

// On exception, remove this channel from the selector

try {
} catch( IOException ie2 ) { System.out.println( ie2 ); }

System.out.println( "Closed "+sc );

private boolean readData(SocketChannel sc) throws Exception{
buffer.clear(); buffer );

if (buffer.limit()==0) {
return false;

System.out.print(new String(buffer.array()));

return true;

any ideas ??
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't used NIO enough yet to remember off the top of my head, but I believe you can associate a single object instance with each key. Write a class that will hold any state needed (like the HTTP request itself) for each key.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!