簡體   English   中英

線程的nullpointer異常

[英]nullpointer exception for thread

我正在基於互聯網上的tut實現一個tcp java客戶端/服務器應用程序我改變了一些方法並得到nullpointerexception的錯誤

錯誤來自run()。 它在一個擴展Thread類的Connection類中。 run()應該監聽傳入的通信。 我啟動服務器類,聽一個端口。 所以我有一個成功的聯系。 然后,當我嘗試通過run()方法偵聽傳入通信時,應用程序報告錯誤

建立連接並開始:

Connection c = new Connection(host,port);
                Scanner chatConsole = new Scanner(System.in);
                String text = "";

                while (!text.equalsIgnoreCase("halt")){         
                    text = chatConsole.nextLine();
                    c.start();

線程“Thread-1”中的異常java.lang.NullPointerException

運行()

public void run(){//watch for incoming communication
    String msg;

    try{//loop reading lines and display msg
        while ((msg = in.readLine()) != null) {
            System.out.println(msg);
        }
    }catch (IOException e) {
        System.err.println(e);
    }   
}

如果它有助於調試,那么這是該類的構造函數。

public Connection(String iniName, int iniPort){
        host = iniName;
        port = iniPort;

        try {
            server = new Socket(host, port);
        }catch (UnknownHostException e){
            System.err.println(e);
            System.exit(1);
        }

        try{
            stdIn = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(server.getOutputStream(), true); //output stream to server
            BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
        }catch(Exception e){
            System.err.println(e);
        }
    }

謝謝

您的in變量為null,您嘗試使用它:

while ((msg = in.readLine()) != null) {

可能是因為你正在構建它的地方遮蔽它。

BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));

而不是在本地重新聲明變量:

in = new BufferedReader(new InputStreamReader(server.getInputStream()));

無處在你的代碼粘貼好你聲明一個全局場in 這是拋出NullPointerException嗎? in.readLine )。 請確保正確初始化Stream(即將其設為字段,而不是構造函數中的局部變量)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM