我运行客户端时,我的服务器一直收到此错误:
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at MyServer.main(MyServer.java:10)
这是服务器代码:
import java.net.*;
import java.io.*;
public class MyServer{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(40);
Socket clientSocket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
System.out.println(in.readInt());
serverSocket.close();
System.exit(0);
}
}
这是客户端代码:
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 40);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeInt(5);
socket.close();
System.exit(0);
}
}
答案 0 :(得分:2)
在关闭ObjectOutputStream
之前,您应该flush Socket
。
答案 1 :(得分:2)
尝试添加
out.flush();
之前
socket.close();