有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从InputStream读取java NullPointerException

我正在开发一个客户机-服务器游戏,所有步骤都基于从客户机发送请求,然后从服务器接收响应。 有时需要接收异步消息,因此我在客户机中打开一个线程来侦听这些消息

级别广播员:

public class BroadcastReceiver implements Runnable {
    private ClientController clientController;
    private AtomicBoolean running = new AtomicBoolean(false);
    private Thread receiver;

    public BroadcastReceiver(ClientController clientController) {
        this.clientController = clientController;
    }

    public void start() {
        receiver = new Thread(this);
        running.set(true);
        receiver.start();
    }

    public boolean isRunning() {
        return running.get();
    }

    public void stop() {
        running.set(false);
    }

    public void restart() {
        if (!receiver.isAlive()) {
            this.start();
        } else
            System.err.println("Thread already running");
    }

    @Override
    public void run() {
        Response response;
        do {
            response = clientController.getClient().nextResponse();
            if (response != null) {
                response.handle(clientController);
            } else
                running.set(false);
        } while (running.get());
    }
}

这是读取和写入请求/响应的客户端代码

package ingsw.controller.network.socket;

import ingsw.controller.network.commands.Request;
import ingsw.controller.network.commands.RequestWoResponse;
import ingsw.controller.network.commands.Response;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {
    private final String host;
    private final int port;
    private Socket connection;
    private ObjectInputStream objectInputStream;
    private ObjectOutputStream objectOutputStream;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect() throws IOException {
        connection = new Socket(host, port);
        objectOutputStream = new ObjectOutputStream(connection.getOutputStream());
        objectInputStream = new ObjectInputStream(connection.getInputStream());
    }

    public void close() throws IOException {
        objectInputStream.close();
        objectOutputStream.close();
        connection.close();
    }

    void request(Request request) {
        try {
            objectOutputStream.writeObject(request);
        } catch (IOException e) {
            System.err.println("Exception on network: " + e.getMessage());
        }
    }

    void request(RequestWoResponse requestWoResponse) {
        try {
            objectOutputStream.writeObject(requestWoResponse);
        } catch (IOException e) {
            System.err.println("Exception on network: " + e.getMessage());
        }
    }

    Response nextResponse() {
        try {
            Response response = ((Response) objectInputStream.readObject());
            return response;
        } catch (IOException e) {
            System.err.println("Exception on network: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            System.err.println("Wrong deserialization: " + e.getMessage());
        }

        return null;
    }
}

最后,这是服务器部分,一个服务器控制器,它处理每个请求并返回响应(为了简洁起见,我不能在这里发布每个类,因为项目非常长且复杂)

    package ingsw.controller.network.socket;

import ingsw.controller.network.Message;
import ingsw.controller.network.commands.*;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.rmi.RemoteException;
import java.util.List;

public class ClientHandler implements Runnable, UserObserver {
    private Socket clientSocket;
    private final ObjectInputStream objectInputStream;
    private final ObjectOutputStream objectOutputStream;
    private boolean stop;

    private ServerController serverController;

    public ClientHandler(Socket clientSocket) throws IOException {
        this.clientSocket = clientSocket;
        this.objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
        this.objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
        this.serverController = new ServerController(this);
    }

    /**
     * Method that receives every Request sent by the user and passes them to the ServerController
     * and then waits for the Response given by the ServerController and handles it
     */
    @Override
    public void run() {
        try {
            do {
                Response response = ((Request) objectInputStream.readObject()).handle(serverController);
                if (response != null) {
                    respond(response);
                }
            } while (!stop);
        } catch (Exception e) {
            // TODO Handle Excpetions
        }
    }

    /**
     * Method that serializes objects and sends them to the other end of the connection
     * @param response response to send
     */
    private void respond(Response response) {
        try {
            objectOutputStream.writeObject(response);
        } catch (IOException e) {
            System.err.println(e.getClass().getSimpleName() + " - " + e.getMessage());
        }
    }

    public void stop() {
        stop = true;
    }

    /**
     * Method that closes ClientHandler connection
     */
    public void close() {
        stop = true;
        if (objectInputStream != null) {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                System.err.println("Errors in closing - " + e.getMessage());
            }
        }

        if (objectOutputStream != null) {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                System.err.println("Errors in closing - " + e.getMessage());
            }
        }

        try {
            clientSocket.close();
        } catch (IOException e) {
            System.err.println("Errors in closing - " + e.getMessage());
        }
    }

    /*
    *
    * USER OBSERVER METHODS
    *
   */

    @Override
    public void onJoin(int numberOfConnectedUsers) {
        respond(new IntegerResponse(numberOfConnectedUsers));
    }

    @Override
    public void sendMessage(Message message) {
        respond(new MessageResponse(message));
    }

    @Override
    public void receiveDraftNotification() {
        //TODO implement first draft notification from server (button on the view)
    }

    @Override
    public void sendResponse(DiceNotification diceNotification) {
        //TODO send the list of dice (for now only the drafted dice)
    }

    @Override
    public void sendResponse(CreateMatchResponse createMatchResponse) {
        respond(createMatchResponse);
    }

    @Override
    public void activateTurnNotification(List<Boolean[][]> booleanListGrid) {
        //TODO
    }
}

我在这里遇到的问题是,在运行广播程序(它只需按照我的意愿多次读取inputstream)之后,似乎无法使用nextResponse()方法读取inputstream

调用方法的顺序是登录、打开广播、创建匹配,最后是加入匹配(引发异常)

用这种方法

@Override
public boolean joinExistingMatch(String matchName) {
    broadcastReceiver.stop();
    generalPurposeBoolean = false;
    client.request(new JoinMatchRequest(matchName));
    client.nextResponse().handle(this);

    return generalPurposeBoolean;
}

当我试图处理客户机时,会出现NullPointerException。nextResponse(),我已多次调试该应用程序,在运行BroadcastReceiver后,输入流似乎无法正确读取流

这是抛出的例外:

    Exception on network: invalid type code: 00
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 48 more
Caused by: java.lang.NullPointerException
    at ingsw.controller.network.socket.ClientController.joinExistingMatch(ClientController.java:60)
    at ingsw.view.LobbyController.onJoinPressed(LobbyController.java:129)
    ... 58 more

对此有何解释


共 (0) 个答案