简体   繁体   English

Java 7 AsynchronousSocketChannel

[英]Java 7 AsynchronousSocketChannel

I'm using the java 7 AsynchronousSocketChannel to write a simple client server app. 我正在使用java 7 AsynchronousSocketChannel编写一个简单的客户端服务器应用程序。 Once the connection is made, I start a thread on the server which initializes I/O streams with: 建立连接后,我在服务器上启动一个线程,用以初始化I / O流:

    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. 任何其他3种组合都可以正常工作,这意味着,首先初始化输出流,或者首先输入输出流,然后输出另一种输出流。

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. 感谢您对此的任何见解。

When initializing, ObjectOutputStream/ObjectInputStream pair exchange hidden service messages. 初始化时,ObjectOutputStream / ObjectInputStream对交换隐藏的服务消息。 Initialization finishes after the exchange. 交换后初始化完成。 This means, that when one side opens ObjectOutputStream, the other side has to open ObjectInputStream, and vice versa. 这意味着,当一方打开ObjectOutputStream时,另一方必须打开ObjectInputStream,反之亦然。

BTW if you use a thread per connection, what is the sense to use AsynchronousSocketChannel , and mot plain socket? 顺便说一句,如果你每个连接使用一个线程,使用AsynchronousSocketChannel和mot plain socket是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM