user3125878
user3125878

Reputation: 35

Java 7 AsynchronousSocketChannel

I'm using the java 7 AsynchronousSocketChannel to write a simple client server app. Once the connection is made, I start a thread on the server which initializes I/O streams with:

    ObjectInputStream  is;
    ObjectOutputStream os;

    is = new ObjectInputStream( Channels.newInputStream( client ) );
    System.out.println( "Got is" );
    os = new ObjectOutputStream( Channels.newOutputStream( client ) );
    System.out.println( "Got os" );

The client uses the same code on its end.

The problem I'm having is that if both initialize the input stream first and then the output stream, both sides hang. Any of the other 3 combinations works ok, meaning, both initialize output stream first or one does input and the other does output first.

Anybody have any idea why this might be ?

The client gets a connection with:

    InetSocketAddress addr = new InetSocketAddress( host, port );
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    Future<Void> future = channel.connect( addr );
    future.get();  // blocks till connection is established

The server listens with:

    InetSocketAddress addr = new InetSocketAddress( port );
    AsynchronousServerSocketChannel server
        = AsynchronousServerSocketChannel.open().bind( addr );

    Future<AsynchronousSocketChannel> future = server.accept();
    client = future.get( 5, TimeUnit.SECONDS );
    if ( client != null ) {
        // open streams as shown above ...
    }

Thanks for any insight into this.

Upvotes: 0

Views: 646

Answers (1)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13525

When initializing, ObjectOutputStream/ObjectInputStream pair exchange hidden service messages. Initialization finishes after the exchange. This means, that when one side opens ObjectOutputStream, the other side has to open ObjectInputStream, and vice versa.

BTW if you use a thread per connection, what is the sense to use AsynchronousSocketChannel , and mot plain socket?

Upvotes: 2

Related Questions