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);
}
}
}
}
一切處理索引越界異常的工作真的很好,直到我退出,從客戶端連接它給這個錯誤如何從ByteBuffer
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連接的所有套接字
你想做什麼?你知道'IndexOutOfBoundsException'是什麼嗎?你知道爲什麼它被扔在你的案件? –
當我用命令telnet localhost 64000關閉telnet窗口時,程序崩潰。我想修復崩潰,所以它不會發生。 –