This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Sockets and Internet Protocols and the fly likes Detecting connection request Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Detecting connection request" Watch "Detecting connection request" New topic

Detecting connection request

Haris Karameh
Ranch Hand

Joined: Oct 17, 2002
Posts: 38
I have to build TCP proxy functionality. I am trying to use NIO classes.
Generally this is what I want to do:
1. Source device tries to connect to the proxy port A
2. the proxy tries to connect the destination device on port B
3. if the proxy succeeds establishing a connection, then the proxy accepts the source connection otherwise rejects it.

Well , I tried this:
InetSocketAddress addr1 = new InetSocketAddress(RPORT);
ServerSocketChannel sch1 =;

Selector selector =;
sch1.register(selector, SelectionKey.OP_ACCEPT);
sch2.register(selector, SelectionKey.OP_ACCEPT);
while ( > 0) {
Set keys = selector.selectedKeys();
Iterator i = keys.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey);
ServerSocketChannel sch = (ServerSocketChannel);//<-- connection already accepted

SocketChannel ch = sch.accept();


The problem is in a fact that sch accepts connection before the code perfoms

In this moment the source device dumps data to the proxy even the destination connection has not been established.
I wanted accept() to be delayed until it is programatically executed. How do I do this?

I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Detecting connection request
jQuery in Action, 3rd edition