Strange SocketChannel.connect() behaviour
I currently have a client that is connecting to a server, however the
connect() is completing before the server even performs the accept. Should
the connect not be waiting for the server accept before indicating it is
complete?
This is being run under Java 5.0 and does the same when run on any of 3
systems: two Linux boxes (RHEL 3 and Fedora 5) and Win2000.
The following are two minimal apps that show the behaviour.
Server.java
-------------------------------------------------------------
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class Server
{
public static void main(
String[] args )
{
try
{
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking( false );
ssChannel.socket().bind( new InetSocketAddress( 2020 ) );
SocketChannel sChannel = null;
while ( sChannel == null )
{
sChannel = ssChannel.accept();
}
System.out.println( "Received connect from " + sChannel );
}
catch ( IOException e )
{
}
}
}
Client.java
-------------------------------------------------------------
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class Client
{
public static void main(
String[] args )
{
try
{
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking( false );
sChannel.connect( new InetSocketAddress( "127.0.0.1", 2020 ) );
while ( ! sChannel.finishConnect() )
{
// Could be doing something else
}
System.out.println( "Socket channel is now ready to use" );
}
catch ( IOException e )
{
}
}
}
When run as shown, the server prints the channel info, after responding to
the accept, and then terminates while the client prints out it is ready.
If I comment out the accept() in the server, it runs forever, not accepting
any connects, however the client still reports the channel is ready. I also
see this when I use a selector with OP_CONNECT and when I use all the isXXX
methods I can think of.
Any and all suggestions will be appreciated, especially those that tell me
how to get the behaviour that is expected.
Thanks,
Dave