如何处理ByteBuffer中的索引越界异常

时间:2015-10-08 00:38:38

标签: java nio bytebuffer

package server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Server {
    public static void main(String... args) throws IOException  {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.socket().bind(new InetSocketAddress(64000));
        Selector selector = Selector.open();
        server.register(selector, SelectionKey.OP_ACCEPT);
        while(server.isOpen()){
            selector.select();
            for(SelectionKey key : selector.selectedKeys()){
                if(key.isAcceptable()){
                    SocketChannel socket = server.accept();
                    socket.configureBlocking(false);
                    socket.register(selector, SelectionKey.OP_READ);
                }
                if(key.isReadable()){
                    SocketChannel socket = (SocketChannel)key.channel();
                    ByteBuffer socketbuffer = ByteBuffer.allocate(100);
                    int read = socket.read(socketbuffer);
                    byte[]stringarray = socketbuffer.array();
                    socket.write(ByteBuffer.wrap(stringarray, 0, read));
                    System.out.print(new String(stringarray, 0, read));
                }
                selector.selectedKeys().remove(key);
            }
        }
    }
}

一切正常,直到我从客户端退出连接它才会出现此错误

Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.nio.ByteBuffer.wrap(ByteBuffer.java:375)
at server.Server.main(Server.java:31)

Java结果:1

当我收到此错误时,它会关闭我用telnet连接的所有套接字

1 个答案:

答案 0 :(得分:1)

您没有检查socket.read()的返回值,如果已到达流的末尾,则返回-1 http://docs.oracle.com/javase/7/docs/api/java/nio/channels/SocketChannel.html#read(java.nio.ByteBuffer)

尝试添加此

int read = socket.read(socketbuffer); //after here
if(read == -1){
    socket.close();
}else{ //the logic is weird after this so I just changed it
    socketbuffer.flip();
    System.out.print(new String(socketbuffer.array(), socketbuffer.position(), socketbuffer.limit()));
    socket.write(socketbuffer);
    socketbuffer.clear();

}

在使用密钥之前,您还应检查密钥是否有效。