我想制作服务器客户端应用程序。我设置了一切,我得到了这个错误。我希望应用程序等到我获得更多数据。
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)
就行:
listener.Received(inputstream.readObject(), id.ID);
服务器代码:
isrunning = true;
Thread input = new Thread(new Runnable(){
@Override
public void run() {
try{
ServerSocket Server = new ServerSocket(LocalPort);
while(isrunning){
Socket socket = Server.accept();
ObjectOutputStream outputstream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream inputstream = new ObjectInputStream(socket.getInputStream());
Object obj = inputstream.readObject();
if(obj instanceof ID){
ID id = (ID) obj;
if(connctedChecker(id.ID)){
ID myid = new ID(ID, LocalIP, LocalPort);
outputstream.writeObject(myid);
connect(id.IP, id.Port);
listener.Connected(id.ID);
do{
listener.Received(inputstream.readObject(), id.ID);
}while(socket.isConnected());
listener.Disconnected(id.ID);
closeConnection(id.ID);
}
}
inputstream.close();
outputstream.close();
socket.close();
}
Server.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
input.start();
客户代码:
output = new Thread(new Runnable(){
@Override
public void run(){
try {
socket = new Socket(RemoteIP, RemotePort);
inputstream = new ObjectInputStream(socket.getInputStream());
outputstream = new ObjectOutputStream(socket.getOutputStream());
ID id = new ID(ID, LocalIP, LocalPort);
outputstream.writeObject(id);
outputstream.flush();
Object obj = inputstream.readObject();
if(obj instanceof ID){
ID inid = (ID) obj;
RemoteID = inid.ID;
}
while(socket.isConnected()){
Object object = queue.take();
outputstream.writeObject(object);
outputstream.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
听众:
public class Listener {
public void Connected(UUID ID){
}
public void Received(Object object, UUID ID){
}
public void Disconnected(UUID ID){
}
}
答案 0 :(得分:2)
do{
listener.Received(inputstream.readObject(), id.ID);
}while(socket.isConnected());
除非你的socket / inputstream有无限数量的对象要发送,否则它迟早会耗尽对象。这就是发生的事情。它在EOFException的javadoc中说得很对。
表示在输入过程中意外地达到了文件结尾或流结束。
此异常主要由数据输入流用于信号流的结束。请注意,许多其他输入操作在流末尾返回特殊值,而不是抛出异常。
答案 1 :(得分:0)
WorkerMessageToMaster中使用的所有对象以及WorkerMessageToMaster本身是否都可序列化?您要与ObjectStreams一起发送的每个对象都必须实现可序列化,并且其所有子代都必须实现它。字符串以及原始数据类型(int,float等)都可以序列化,而无需执行任何操作。但是,如果您使用自己的类,则它们必须实现可序列化。