2013-08-19 58 views
0

每當我運行我的聊天服務器時,它一直運行到客戶端連接,然後我得到一個空指針例外 connections.add(socket); 崩潰它,然後每次運行它時都會發生這種情況。 我知道我的客戶端是很好,因爲我在幾個月前看過關於如何做到這一點的教程和服務器與我的客戶工作沒有崩潰Java Socket ArrayList空指針異常

private static ServerSocket server; 
private static Socket socket; 
private static Scanner input; 
private static PrintWriter output; 

private static final int port = 444; 
private static String message; 
private static ArrayList<Socket> connections; 
private static Server serverClass; 

public Server() { 

    message = ""; 
    connections = new ArrayList<Socket>(); 
    serverClass = new Server(); 

} 

public void run() { 

    try { 

     try { 

      input = new Scanner(socket.getInputStream()); 
      output = new PrintWriter(socket.getOutputStream()); 

      while(true) { 

       checkConnection(); 

       if(!input.hasNext()) { 

        return; 

       } 

       message = input.nextLine(); 
       System.out.println("Client said: " + message); 

       for(int i = 1; i <= connections.size(); i++) { 

        Socket tempSock = (Socket) connections.get(i - 1); 
        output.println(message); 
        output.flush(); 

       } 

      } 

     } 
     finally { 

      socket.close(); 

     } 

    } 
    catch(Exception e) { 

     System.out.print(e); 

    } 

} 

public void checkConnection() throws IOException { 

    if(!socket.isConnected()) { 

     for(int i = 1; i <= connections.size(); i++) { 

      if(connections.get(i) == socket) { 

       connections.remove(i); 

      } 

     } 

     for(int i = 1; i <= connections.size(); i++) { 

      Socket disconnectedUser = (Socket) connections.get(i - 1); 
      System.out.println(disconnectedUser + " has Disconnected!"); 

     } 

    } 

} 

public static void main(String[] args) throws IOException{ 

    try { 

     server = new ServerSocket(port); 
     System.out.println("Waiting for Clients... "); 

     while(true) { 

      socket = server.accept(); 
      connections.add(socket); 
      System.out.println("Client connected from: " + socket.getLocalAddress().getHostName()); 

      Thread thread = new Thread(serverClass); 
      thread.start(); 

     } 

    } 
    catch(Exception e) { 

     e.printStackTrace(); 

    } 

} 
+0

您是否調試過並查看連接中是否有任何值? – Krishna

+1

@ mdoran3844他正在接受套接字,而不是連接它。除非你錯誤地斷言'ArrayList'不能有空元素,否則你的問題是無關緊要的。 – EJP

回答

3

如果您在connections.add(socket),那隻能是因爲得到一個NPE connections爲空。它是什麼,因爲你還沒有構建Server的實例:而是你試圖從main().執行它的所有代碼你唯一呼叫new Server()的地方在Server,的構造函數裏面,你根本就沒有執行過,因爲你將從無限遞歸獲得StackOverflowError

此代碼是一個真正的混亂:

  • 修復無限遞歸
  • 構建的Server一個實例在main()方法
  • 使connections非靜態
  • 使socket在一個局部變量接受循環
  • 修復您的循環以重複從0到connections.size()-1

並重試。