我正在编写一个简单的轮盘游戏,一次可以让多个玩家参与其中。
我试图反序列化.dat文件players.dat
,但是我得到的FileNotFoundException
我怀疑是由于我的主线程同时运行到另一个线程。
我的主文件(注意readObj
只是一个方便的方法,它使用ObjectInputStream来读取对象):
Collection<Player> mPlayerList = null;
try {
connectToServer();
} catch (IOException e) {
System.err.println("IO exception when trying to write/connect to server");
e.printStackTrace();
}
// read input stream and attempt to deserialize
// stack trace points to the error being from here
try {
mPlayerList = (Collection<Player>) readObj("players.dat");
} catch (IOException e) {
System.err.println("IO exception when trying to read master player list");
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
System.err.println("Class not found exception when trying to read master player list");
e.printStackTrace();
System.exit(1);
}
在我的第一个try
语句中,我尝试连接到运行我的计算机的服务器:
public class GameEngineServerStub {
public static void main(String[] args) throws IOException {
GameEngineImpl myEngine = new GameEngineImpl();
int portNumber = 4444;
boolean listening = true;
// While statement loops forever, waiting for a client to connect.
// Once client connects, accept, create a new Thread, pass the socket to it, and requests it to start
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new GameEngineServerStubThread(serverSocket.accept(), myEngine).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port 4444");
System.exit(-1);
}
}
}
服务器启动此线程,该线程负责从另一个文件请求Collection<Player>
对象,并尝试对其进行序列化。
public void run() {
try (
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
Collection<Player> currentPlayers = engine.getAllPlayers();
try {
ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("players.dat"));
objOut.writeObject(currentPlayers);
} catch (IOException e) {
System.err.println("IO Exception when trying to get master player list!");
e.printStackTrace();
System.exit(1);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
我假设我需要暂停main
线程,等待序列化线程完成,但我不确定如何执行此操作。