2015-10-08 61 views
0
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連接的所有套接字

+0

你想做什麼?你知道'IndexOutOfBoundsException'是什麼嗎?你知道爲什麼它被扔在你的案件? –

+0

當我用命令telnet localhost 64000關閉telnet窗口時,程序崩潰。我想修復崩潰,所以它不會發生。 –

回答

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(); 

} 

您也應該檢查是否的關鍵是使用它之前有效。

+0

關閉通道就足夠了。它取消了密鑰。你不需要這樣做。在寫入之後,您還必須「壓縮()」或「清除()」ByteBuffer。 – EJP