Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

nio and http request

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

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 www.google.fr, 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()){
try{
int num = _selector.select();

if (num == 0)
continue;

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

if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
SelectionKey.OP_ACCEPT)
incomingConnection();
else if ((key.readyOps() & SelectionKey.OP_READ) ==
SelectionKey.OP_READ)
incomingData(key);
}

keys.clear();

}catch(Exception e){
e.printStackTrace();
setRun(false);
}
}
}

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)key.channel();
boolean ok = readData(sc);

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

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

} catch( Exception ie ) {

// On exception, remove this channel from the selector
key.cancel();

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

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

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

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

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

return true;
}

any ideas ??
thnx
 
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic