SocketChannel:中断关闭所有打开的通道

时间:2012-12-17 09:59:38

标签: java socketchannel

我有以下情况:

  • 服务器打开ServerSocketChannel并接受客户端连接。
  • 每个连接(socketA)都在新线程中处理。
  • 在线程内部,我打开一个连接另一台服务器的新SocketChannel(socketB)。
  • 此时原始客户端连接(socketA)处于空闲状态。
  • 新的SocketChannel从服务器读取数据(阻塞)。

现在我打断了线程。我预计socketB将被中断和关闭,socketA将继续工作。不幸的是socketA也会被打断。

知道可能是什么问题吗?

我使用以下测试方法来重现行为:

private void testServerSocket() throws IOException, InterruptedException
{
    final InetSocketAddress     address         = new InetSocketAddress( "localhost", 12345 );
    final ServerSocketChannel   serverChannel   = ServerSocketChannel.open();
    serverChannel.socket().bind( address );

    final SocketChannel socketChannel   = serverChannel.accept();

    // start communication in new thread
    final Thread    thread  = new Thread( new Runnable() { @Override public void run() { testWrite( socketChannel ); } } );

    thread.start();

    // wait a little bit
    Thread.sleep( 5000 );

    // interrupt thread, will interrupt the socketChannel.read in testRead()
    thread.interrupt();
    thread.join();

    socketChannel.close();
    serverChannel.close();
}

void testWrite( SocketChannel socketA )
{
    try
    {
        // write to client
        socketA.write( ByteBuffer.wrap( "0123456789".getBytes() ) );

        // open new socket to another server
        testRead();

        // throws ClosedByInterruptException
        socketA.write( ByteBuffer.wrap( "0123456789".getBytes() ) );
    }
    catch( final IOException e )
    {
        e.printStackTrace();
    }
}

void testRead()
{
    try
    {
        final InetSocketAddress address   = new InetSocketAddress( "localhost", 12346 );
        final SocketChannel     socketB   = SocketChannel.open( address );

        // server doesn't send, so this call will block and interrupted 
        socketB.read( ByteBuffer.wrap( new byte[10] ) );

        socketB.close();
    }
    catch( final IOException e )
    {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在Thread.interrupted()中的IOException之后调用testRead()来清除线程的中断状态。实际上你应该抓住ClosedByInterruptException并在那里做。否则,条件仍然存在并且也会中断写入。