你好我已经搜索了很多关于这个错误,但是还没找到答案。 当我尝试发送一个对象并接收我之前发送给服务器的对象时,我不断收到此错误。我想在我的客户端类中做所有这些。我找到了一些答案,说你必须在写()对象之后刷新()你的objectOutputStream,以使objectInputStream工作。
public void createAndListenSocket()抛出ClassNotFoundException {
//sending part
try {
Socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] incomingData = new byte[1024];
Triangle student = new Triangle(1, 2, 45);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(student);
os.flush();
byte[] data = outputStream.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
Socket.send(sendPacket);
System.out.println("Message sent from client");
//receive part
while (true) {
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
Socket.receive(incomingPacket);
byte[] datareceived = incomingPacket.getData();
ByteArrayInputStream in = new ByteArrayInputStream(datareceived);
ObjectInputStream is = new ObjectInputStream(in);
receivedfromServer = (Triangle) is.readObject();
reply = "Triangle received from the server is:" + " "+receivedfromServer.theta;
Thread.sleep(2000);
}
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}