Я занимаюсь разработкой игры клиент-сервер, и все шаги основаны на отправке запроса от клиента и после этого получении ответа от сервера.Иногда необходимо получать асинхронные сообщения, поэтому я открываю поток на клиенте, который прослушивает эти сообщения.
Класс Broadcaster:
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;
}
}
и, наконец, это серверная часть, ServerController, который обрабатывает каждый запрос и возвращает ответ (для краткости я не могу опубликовать каждый класс здесь, так как проект довольно длинныйи сложный)
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
}
}
Проблема, с которой я сталкиваюсь, заключается в том, что после запуска Broadcaster, который просто читает из inputtream столько раз, сколько я хочу, кажется, что я не могу читать из inputtream с помощью nextResponse() метод.
Порядок, в котором вызываются методы, называется «Вход в систему», включает вещатель, создает совпадение и, наконец, сопоставление соединения (которое вызывает исключение).
В этом методе
@Override
public boolean joinExistingMatch(String matchName) {
broadcastReceiver.stop();
generalPurposeBoolean = false;
client.request(new JoinMatchRequest(matchName));
client.nextResponse().handle(this);
return generalPurposeBoolean;
}
Я получаю исключение NullPointerException при попытке обработать client.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
Есть лиобъяснение этому?