我正在建立一个新的服务器-客户端系统。在这里,来自客户端的对象将被发送到服务器。并且在接收到对象之后,服务器将向客户端发送一个字符串。
服务器在这里成功读取对象。但是,当客户端想要读取服务器发送的字符串时,它将引发EOFException。
客户端
public static void main(String args[]) throws IOException, EOFException {
try (Socket socket = new Socket("localhost", 1254)) {
OutputStream outputStream = socket.getOutputStream();
InputStream s1In;
DataInputStream dis;
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
s1In = socket.getInputStream();
dis = new DataInputStream(s1In);
Frame frame = new Frame();
frame.setData("test");
objectOutputStream.writeObject(frame);
String st = "";
while(dis.available() >0){
st = dis.readUTF();
}
System.out.println(st);
}
dis.close();
s1In.close();
}
}
服务器端
public static void main(String args[]) throws IOException, ClassNotFoundException {
ServerSocket s = new ServerSocket(1254);
Socket socket = s.accept();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//input stream
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Frame frame = new Frame();
frame = (Frame) objectInputStream.readObject();
String data = frame.getData();
System.out.println(data);
// Send a string!
DataOutputStream dos = new DataOutputStream (outputStream);
dos.writeUTF("Received");
dos.close();
objectOutputStream.close();
outputStream.close();
objectInputStream.close();
inputStream.close();
socket.close();
}
客户端错误
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at computernetworklab.Client.main(Client.java:38)
/home/shahad/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)