java - java客户端中的NullPointer异常?

标签 java eclipse sockets exception nullpointerexception

我正在编写一个简单的客户端,但我总是在以下位置收到 NullPointerException:

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

这是我的代码:

public class ClientTest {

public static String server = "127.0.0.1";
public static int sport = 11111;
public static int cport = 11111;
private static String clientname="";
public static ExecutorService pool = Executors.newCachedThreadPool();
public static BufferedReader in = null;
public static PrintWriter out = null;
public static Socket socket = null;

public ClientTest(){
    this.clientname="";
}


public static void main(String[] args) {

    try {
        socket = new Socket(server, sport);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch(IOException e) {
        System.out.println("could not create connection:\n" + e);
        try {
            if(socket != null) socket.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    pool.execute(new Communicator());

}

public static class Communicator implements Runnable {
    @Override
    public void run() {
        String input = "";
        try {
            while ((input = in.readLine()) != null) {//here  i get the NPException
                StringTokenizer tokenizer = new StringTokenizer(input);
                tokenizer.nextToken();

                if(input.startsWith("!open")) {
                    if(tokenizer.hasMoreTokens()) System.out.print(tokenizer.nextToken() + "> ");
                    else System.out.print("> ");
                } 
                else if(input.startsWith("!exit")) {
                    System.out.print("Hallo hallo");
                } 
            }
        } catch(IOException e) {
            System.out.println("An error as occurred while reading from server - \n" + e);
        }
    }

}


}

为什么我会收到NullPointerException?我仍在初始化字符串输入。

最佳答案

My question is, why do I get the NP Exception, I am still initializing the String input!

如果 in 为 null,您将得到一个 NullPointerException ......这当然有可能。毕竟,如果 main 的第一部分中的任何内容抛出异常,您可以捕获它,将其打印出来......然后继续!因此,如果 socket.getOutputStream() 抛出异常,inout 都将为 null。

寓意:捕获异常并像什么都没发生一样继续很少是一个好主意。

关于java - java客户端中的NullPointer异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922893/

相关文章:

Python SocketServer 适用于本地主机但不适用于服务器

检查套接字监听积压队列是否为空

java - CompressBackupUtil 不备份 blob

java - CDI 中的 session 范围是如何实现的?

java - 使用 Java 将矩阵乘以相同的幂

c++ - eclipse C++。包含带有类的 .h 文件。 "Symbol ' [类 ]' could not be resolved"

java - Eclipse 异常与 java.lang.OutOfMemoryError : Java heap space

java - 在eclipse中调试时调用类实例方法

java - 如何将测试仪返回到开头要求用户输入欧元/英镑/加元

java - 从套接字读取字节