简体   繁体   English

将对象写入 ObjectOutputStream 不起作用

[英]Writing object into ObjectOutputStream doesn't work

i'm writing (testing) a simple client-server application where i need to send some object via socket's ObjectOutputStream and next read it via socket't ObjectInputStream.我正在编写(测试)一个简单的客户端 - 服务器应用程序,我需要通过套接字的 ObjectOutputStream 发送一些对象,然后通过套接字的 ObjectInputStream 读取它。 The problem is that the ObjectOutputStream writeObject method doesn't work properly (or maybe i'm doing something wrong ...).问题是 ObjectOutputStream writeObject 方法不能正常工作(或者我做错了什么......)。 I'm doing writing and reading in the same method.我正在以相同的方法进行写作和阅读。

java -version: java - 版本:

java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)

This is my code:这是我的代码:

ServerTest.java服务器测试程序

ExecutorService tp = Executors.newFixedThreadPool(2);
public ServerTest(String info) {
    System.out.println("SERVER TEST HAVE BEEN STARTED FROM " + info);
    try {
        System.out.println("Starting server ...");
        tp.submit(new ServerTask());
        System.out.println("Server started ...");
        Thread.sleep(1000);
        System.out.println("Starting client ...");
        tp.submit(new Client(new Socket("localhost", 3333)));
        System.out.println("Client started at localhost on port 3333 ...");
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(ServerTest.class.getName()).log(Level.SEVERE, null, ex);
    } 
}
public static void main(String[] args) {
    try {
        new ServerTest("SERVER TEST MAIN STATIC METHOD");
        Thread.sleep(100000);
    } catch (InterruptedException ex) {
        Logger.getLogger(ServerTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

ClientTask.java (implements Runnable ) ClientTask.java(实现 Runnable )

private Socket socket;
private ObjectOutputStream oos;
private ObjectInputStream ois;    
public ClientTask(Socket socket) {
    System.out.println("CLIENT TASK SOCKET : " + socket);
    this.socket = socket;
    try {
        oos = new ObjectOutputStream(socket.getOutputStream());
        oos.flush();
        ois = new ObjectInputStream(socket.getInputStream());
    } catch (IOException ex) {
        Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@Override
public void run() {
    System.out.println("client task running ...");
    for (int i = 0; i < 1; i++) {
        try {
            Thread.sleep(1000);
            SimpleObject so = new SimpleObject(100, "test_str");
            System.out.println("Trying to serialize object into output stream...");
            System.out.println("Object to be written " + so.toString());
            oos.writeObject(so);
            oos.flush();
            System.out.println("Check if the object had been serialized properly ...");
            System.out.println("Bytes in stream : " + ois.available());
            if (ois.available() <= 0) {
                System.out.println("Object had not been serialized ...");
                continue;
            }
            System.out.println("Trying to deserialize object from input stream ...");
            SimpleObject desObj = (SimpleObject) ois.readObject();
            System.out.println("Read object: " + desObj.toString());
            System.out.println("Aborting from method ...");
        } catch (InterruptedException ex) {
            Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                ois.close();
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    System.out.println("Exiting client task ...");
}

ServerTask.java (implements Runnable) ServerTask.java(实现 Runnable)

ExecutorService tp = Executors.newFixedThreadPool(10);
@Override
public void run() {
    System.out.println("Server task run start ...");
    try {
        ServerSocket ss = new ServerSocket(3333);
        for (;;) {
            System.out.println("Server socket start ...");
            Socket s = ss.accept();
            s.setSoTimeout(0);
            System.out.println("Connection: " + s.getInetAddress().toString() + " " + s.getPort());
            System.out.println("Starting client task ...");
            tp.submit(new ClientTask(s));
            System.out.println("Client task started ...");
            System.out.println("Server socket end ...");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    System.out.println("Server task run end ...");
}

Client.java (implements Runnable) Client.java(实现 Runnable)

private Socket socket;
private ObjectOutputStream oos;
private ObjectInputStream ois;
public Client(Socket socket) {
    System.out.println("CLIENT SOCKET : " + socket.toString());
    this.socket = socket;
    try {
        oos = new ObjectOutputStream(socket.getOutputStream());
        oos.flush();
        ois = new ObjectInputStream(socket.getInputStream());
    } catch (IOException ex) {
        Logger.getLogger(ClientTask.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@Override
public void run() {
    for (int i = 0; i < 10; i++) {
        //System.out.println("client running ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

SimpleObject.java (implements Serializable) SimpleObject.java(实现可序列化)

private static final long serialVersionUID = 4L;
private Integer integer;
private String string;
public SimpleObject(Integer integer, String string) {
    this.integer = integer;
    this.string = string;
}
//getters,setters, toString method ...

The output is输出是

run:
SERVER TEST HAVE BEEN STARTED FROM SERVER TEST MAIN STATIC METHOD
Starting server ...
Server started ...
Server task run start ...
Server socket start ...
Starting client ...
CLIENT SOCKET : Socket[addr=localhost/127.0.0.1,port=3333,localport=57703]
Connection: /127.0.0.1 57703
Starting client task ...
CLIENT TASK SOCKET : Socket[addr=/127.0.0.1,port=57703,localport=3333]
Client started at localhost on port 3333 ...
Client task started ...
Server socket end ...
Server socket start ...
client task running ...
Trying to serialize object into output stream...
Object to be written SimpleObject{integer=100, string=test_str}
Check if the object had been serialized properly ...
Bytes in stream : 0
Object had not been serialized ...
Exiting client task ...

It's a simple application but it doesn't work ... i can't understand why.这是一个简单的应用程序,但它不起作用......我不明白为什么。 Please help me.请帮我。

Do you want both the client and the server to be using the same input streams?您是否希望客户端和服务器都使用相同的输入流? I would expect the client and server to be on different threads (or, in different java processes), in which case the client output stream would map to the server input stream and the client input stream would map to the server output stream.我希望客户端和服务器在不同的线程上(或者,在不同的 java 进程中),在这种情况下,客户端输出流将映射到服务器输入流,而客户端输入流将映射到服务器输出流。 Here is a good example to follow: baeldung.com/a-guide-to-java-sockets (Note: This is not meant to endorse Baeldun. But the example is good.)这是一个很好的例子:baeldung.com/a-guide-to-java-sockets(注意:这并不意味着支持 Baeldun。但这个例子很好。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM