尝试通过套接字发送arrayList时,在对象输入流初始化(客户端)时获得空指针异常。

客户:

try {
        ObjectInputStream objIn = new ObjectInputStream(
               Client.socket.getInputStream()); // HERE
        library = (ArrayList<Book>) objIn.readObject();
    } catch (IOException e) {

服务器:
try {
    ObjectOutputStream objOut = new ObjectOutputStream(
            this.client.getOutputStream());
    objOut.writeObject(library);
    objOut.flush(); // added later, not helping
}

我一直在尝试通过套接字进行通信两天,但几乎没有成功。我不知道是怎么回事。我计划在有更多时间的时候更好地记录自己,但现在我真的很想了解发生了什么。

编辑
public class Client {

    private static int  port    = 6666;
    private static Socket   socket  = null;

    public Client (int port) {
        Client.port = port;
    }

    public Client () {
    }

    public void establishConnection() {
        try {
            Client.socket = new Socket(InetAddress.getByName(null), Client.port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

服务器:
public void start () {
    (new Thread() {
        public void run() {
            try {
                Server.socket = new ServerSocket(Server.portNumber);
                while (!Server.stop) {
                    Socket client = Server.socket.accept();
                    (new HandleRequest (client)).start();
                }
             ...............


public class HandleRequest extends Thread {

    private Socket client = null;
    private SQL sql_db = new SQL ();

    public HandleRequest (Socket client) {
        this.client = client;
    }

    @Override
    public void run () {
        try {
            if (!this.sql_db.isConnected())
                this.sql_db.connect();
            if (this.client == null) {
                System.out.println("Error: client does not exist, NO idea what's going on");
                return;
            }



            ArrayList<Book> library = this.sql_db.getAllBooks();
            try {
                ObjectOutputStream objOut = new ObjectOutputStream(
                        this.client.getOutputStream());
                objOut.writeObject(library);
                objOut.flush();
            } catch (Exception e) {
                System.out.println("Server error in handling request for whole library!");
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最佳答案

因为NPE在这条线上:

Client.socket.getInputStream());

只有一件事可以导致它。不能是Client,因为那是static。不能是getInputStream(),因为那是一种方法,所以它必须是导致NPE的socket

在这行上:
private static Socket socket = null;

您将socket设置为null。我看到的将其设置为非null的唯一位置是在.establishConnection()方法中,但看不到在哪个位置调用该方法。

因此,您的问题很可能是您没有调用.establishConnection()方法。

关于java - 通过套接字接收数组列表时发生NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20972176/

10-10 07:31