简体   繁体   English

线程的run方法中的NullPointerException

[英]NullPointerException in Thread's run method

I would really appreciate help with my program. 我真的很感谢我的程序的帮助。 It is some sort of chat server with multiple clients. 它是具有多个客户端的某种聊天服务器。 Here's the server code: 这是服务器代码:

package com.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    public static int PORT;
    private ServerSocket server;
    private Socket socket;

    public Server(int port) throws IOException {
        PORT = port;
        server = new ServerSocket(PORT);
        System.out.println("server started");
        try {
            while (true) {
                socket = server.accept();
                try {
                    new ServeClient(socket);
                } catch (IOException e) {
                    socket.close();
                }
            }
        } finally {
            server.close();
        }

    }

    public static void main(String[] args) throws IOException {
        int port = Integer.parseInt(args[0]);
        Server server = new Server(port);
    }

}

I start the server and then create a Client. 我启动服务器,然后创建一个客户端。 The server receives connection socket from socket and creates a ServeClient Thread. 服务器从套接字接收连接套接字,并创建一个ServeClient线程。 Here's ServeClient code: 这是ServeClient代码:

package com.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;

import com.gui.WindowManager;

public class ServeClient extends Thread {
    private final Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private String msg;
    public static final String ENDSTRING = "END";
    public static Vector clients = new Vector();

    public ServeClient(final Socket socket) throws IOException {
        this.socket = socket;
        System.out.println("socket " + socket);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                socket.getOutputStream())), true);
        start();
    }

    public void run() {
        try {
            clients.add(this);
            while (true) {
                msg = in.readLine();
                if (msg == ENDSTRING)
                    break;
                broadcast(msg);
            }
            System.out.println("closing...");
        } catch (IOException e) {
            System.err.println("IO EXCEPTION");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.println("SOCKET NOT CLOSED");
            }
        }
    }

    @SuppressWarnings("deprecation")
    public void broadcast(String msg) {
        synchronized (clients) {
            Enumeration<ServeClient> e = clients.elements();
            while (e.hasMoreElements()) {
                ServeClient serveClient = e.nextElement();
                try {
                    synchronized (serveClient.out) {
                        serveClient.out.println(msg);
                    }
                } catch (Exception eee) {
                    serveClient.stop();
                }
            }
        }
    }
}

What i get is a NullPointerException when ServeClient invokes run() method 当ServeClient调用run()方法时,我得到的是NullPointerException

server started
socket Socket[addr=/127.0.0.1,port=51438,localport=8888]
Exception in thread "Thread-0" java.lang.NullPointerException
    at com.server.ServeClient.run(ServeClient.java:33)

line 33 is the line with first "try" statement in ServeClient run() method 第33行是ServeClient run()方法中第一个“ try”语句的行

com.server.ServeClient.run(ServeClient.java:33)

I don't believe that it's happening at the try. 我不相信尝试时会发生这种情况。

Open up an IDE, turn on debugging, and step through until you can see what's happening. 打开IDE,打开调试,然后逐步进行,直到您看到发生了什么。 That's the fastest way to figure out what you've missed. 这是找出您错过的最快方法。

There's an object that you're assuming is fine that is not. 您假设有一个对象没问题。 Find it. 找到它。

Here's an example of how to do this properly: 以下是如何正确执行此操作的示例:

http://www.kodejava.org/examples/216.html http://www.kodejava.org/examples/216.html

Sorry for necroing such an old issue but it seemed like this problem wasn't resolved, so I'll give a bit of input from my end. 很抱歉取消这样一个老问题,但似乎这个问题没有解决,因此我会从结尾提供一些建议。

I've had a similar problem and the compiler also kept telling me that the problem was at the start() method. 我遇到了类似的问题,编译器也不断告诉我问题出在start()方法上。 However, when I commented out the thread part and just ran the code on the same thread as the UI, the compiler directed me to the real source of the problem: the code inside the thread. 但是,当我注释掉线程部分并只在与UI相同的线程上运行代码时,编译器将我定向到问题的真正根源:线程内的代码。

After making sure the code didn't give an error, I enclosed the code with the original thread code, and it stopped giving me the NullPointerException error. 在确保代码没有给出错误之后,我用原始线程代码将代码括起来,然后停止提供NullPointerException错误。

Hope this helps someone along the way. 希望这可以对某人有所帮助。

Your problem is with the order in which static instance variables are initialised. 您的问题在于初始化静态实例变量的顺序。 Try doing something like: 尝试做类似的事情:

...
private static Vector clients = null;
...
if (clients==null) {
    clients = new Vector(); // consider putting this in a synchronized block
}

before you add the client to the vector. 在将客户端添加到引导程序之前。

Remove the duplicate class declaration in JPanel. 在JPanel中删除重复的类声明。

I was trying to run a timer thread that updated a clock in the main application window. 我试图运行一个计时器线程,该线程在主应用程序窗口中更新了时钟。

I had created the JFrame with Eclipse/WindowBuilder and had followed a tutorial on how to make a timer. 我已经使用Eclipse / WindowBuilder创建了JFrame,并遵循了有关如何制作计时器的教程。 I had copied the declaration of the textfield into the class declaration to make it available for the entire class, but forgot to remove the Class Id in front of the widget definition. 我已将文本字段的声明复制到类声明中,以使其可用于整个类,但忘记了删除小部件定义前面的类ID。 So it still initialized the local instance and not the global one. 因此,它仍然初始化本地实例而不是全局实例。 Thus when I accessed the global one it was still null. 因此,当我访问全局变量时,它仍然为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM