Java中的Java SocketChannel编写(ByteBuffer源码)与Windows不同吗?

时间:2012-03-12 10:09:19

标签: java android socketchannel

当我调试代码包含SocketChannel在Android中编写时,我得到了IllegalArgumentException,但是在Windows中相同的代码没有这个例外,在SocketChannel写的Android和windows之间有区别吗?

更新: (该代码是开源项目frostwire-android(this file in github)的一部分,这部分与vuze 4.5相同,我只是添加一个try {})

private int channelWrite(ByteBuffer buf) throws IOException
{
    int written = 0;
    while(remainingBytesToScatter > 0 && buf.remaining() > 0)
    {
        int currentWritten = 0;
        try{
            currentWritten = channel.write((ByteBuffer)(buf.slice().limit(Math.min(50+rnd.nextInt(100),buf.remaining()))));
        }catch( Exception e ) {
            if(e instanceof IOException) {
                Log.d("", "chanel write IOException " + e.getMessage());
            }else if(e instanceof IOException) {
                Log.d("", "chanel write AsynchronousCloseException " + e.getMessage());
            }else if(e instanceof ClosedByInterruptException) {
                Log.d("", "chanel write ClosedByInterruptException " + e.getMessage());
            }else if(e instanceof ClosedChannelException) {
                Log.d("", "chanel write ClosedChannelException " + e.getMessage());
            }else if(e instanceof NotYetConnectedException) {
                Log.d("", "chanel write ClosedChannelException " + e.getMessage());
            }else {
                // while in second time, reach here
                Log.d("", "chanel write unknown " + e.getMessage());
            }
        }

        if(currentWritten == 0)
            break;
        buf.position(buf.position()+currentWritten);
        remainingBytesToScatter -= currentWritten;
        if(remainingBytesToScatter <= 0)
        {
            remainingBytesToScatter = 0;
            try
            {
                channel.socket().setTcpNoDelay(false);
            } catch (SocketException e)
            {
                Debug.printStackTrace(e);
            }
        }
        written += currentWritten;
    }

    if(buf.remaining() > 0)
        written += channel.write(buf);

    return written;     
}

1 个答案:

答案 0 :(得分:0)

行为由同一个合同(标准库文档)定义,并且该文档没有为任何特定于实现的解释提供空间,因此您的问题的答案必须是,不,行为之间应该没有区别Android和Windows上的行为。

顺便说一句,the documentation并未说该方法可能会抛出IllegalArgumentException。你确定从该方法抛出了异常吗?我建议你为此提供一个SSCCE。