這是我第一次使用java聯網。我必須將它用於我正在進行的項目,這是一個簡單的紙牌遊戲。我的服務器和客戶端將會在打印「已收到連接」時進行通信。但是,這條線後,會出現以下錯誤:java聯網中的EOFException
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at ClientConnectionManager.reciveData(ClientConnectionManager.java:49)
at LogicThread.getHandSize(GameLogic.java:22)
at LogicThread.run(GameLogic.java:16)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-4" java.lang.NullPointerException
at LogicThread.getHandSize(GameLogic.java:22)
at LogicThread.run(GameLogic.java:16)
at java.lang.Thread.run(Unknown Source)
有問題的類是:
static ObjectInputStream input;
static ObjectOutputStream output;
static Socket socket;
public static void connectToServer(){
try {
System.out.println("connecting");
socket = new Socket(ip, port);
input = new ObjectInputStream(socket.getInputStream());
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
System.out.println("connected");
reciveData();
logic.startLogic();
//listenForData();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object reciveData(){
try {
Object obj = input.readObject(); - Error is on this line
System.out.println(obj);
return obj;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return null;
}
用於發送數據的服務器代碼:
ServerSocket server;
server = new ServerSocket(2302);
Socket connection;
connection = server.accept();
output = new ObjectOutputStream(connection.getOutputStream());
public void sendData(Object data){
try {
output.writeObject(data);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
我不知道是什麼原因導致這因爲服務器發送客戶收到的「已收到的連接」,並且沒有問題並進行打印。但是,來自connectToServer()方法之外的任何調用都會導致上述錯誤。
我們也需要查看服務器端代碼。 – EJP
@EJP yea忘了它只是加了它 –
EOFException是文件結束異常。您已完成閱讀流中的所有內容,並嘗試再次閱讀。 –