socketexception:序列化时连接重置

k4emjkb1  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(463)

我有一个基本的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();
zmeyuzjn

zmeyuzjn1#

找到了解决办法。我忘了在客户端设置objectoutputstream的close()。

相关问题