为什么我的ObjectInput / OutputStrem实例不创建?

问题描述 投票:0回答:1

我正在学习套接字,我在做一个简短的示例来说明如何通过Java套接字发送可序列化的对象。问题是当我同时实例化输入和输出流(ObjectOutputStreamObjectInputStream)时。该程序不会继续进行。我想交换我在服务器和客户端中创建的类User中的对象。

这是我的服务器程序:

public class Main {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        ServerSocket server = new ServerSocket(3333);

        Socket client = server.accept();

        ObjectInputStream objectInput = new ObjectInputStream(client.getInputStream());
        ObjectOutputStream objectOutput = new ObjectOutputStream(client.getOutputStream());

        System.out.println("Instances created");     //Doesn't print on execution

        User user = (User)objectInput.readObject();
        System.out.println(user.toString());

        client.close();
        server.close();
    }
}

这是客户端程序:

public class Main {

    public static void main(String[] args) throws IOException {

        Socket server = new Socket("here I wrote my IP", 3333);
        User user = new User("Me", "[email protected]", 20);

        ObjectInputStream objectInput = new ObjectInputStream(server.getInputStream());
        ObjectOutputStream objectOutput = new ObjectOutputStream(server.getOutputStream());

        System.out.println("Instances created");    //Doesn't print on execution

        objectOutput.writeObject(user);

        server.close();
    }
}

当我执行服务器然后执行客户端时,两个程序都继续执行,但是控制台上没有任何显示。甚至没有System.out.println("Instances created");

为什么?我做错什么了吗?

如果您想知道,类User看起来像这样:

public class User implements Serializable {
    private String name;
    private String email;
    private int edad;

    public User (String name, String email, int edad) {
        this.name = name;
        this.email = email;
        this.edad = edad;
    }

    @Override
    public String toString() {
        return name + " (" + email + "), " + edad + " años";
    }
}
java sockets objectinputstream objectoutputstream
1个回答
1
投票
ObjectInputStream将阻止尝试读取客户端和服务器上的标头。您应该能够从堆栈跟踪中看到它。
© www.soinside.com 2019 - 2024. All rights reserved.