问题描述
我有一个基本的TCP连接,我通过串行化将一个对象从客户端发送到服务器。但是执行此简单任务时出现错误,下面是代码:
客户:
public client() throws IOException{
Socket socket = new Socket("127.0.0.1",4390);
System.out.println("Client connected with server");
Student student = new Student(1,"jemoi","lerry");
ObjectOutputStream oos = new ObjectOutputStream(socket.getoutputStream());
oos.writeObject(student);
}
服务器:
public server() throws IOException,ClassNotFoundException{
ServerSocket serverSocket = new ServerSocket(4390);
System.out.println("Server initialized successfully");
Socket socket = serverSocket.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Student student = (Student)ois.readobject();
System.out.println("Object send from client: " + student.getFirstName());
}
错误:
Exception in thread "main" java.net.socketException: Connection reset
错误发生在行:
Student student = (Student)ois.readobject();
解决方法
找到了解决方案。我忘了在客户端的ObjectOutputStream中设置close()。