gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:05:29 25 4
gpt4 key购买 nike

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 连接的所有套接字

最佳答案

您没有检查 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();

}

您还应该在使用 key 之前检查它是否有效。

关于java - 如何处理 ByteBuffer 中的索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33004736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com