通过网络和字节数组序列化/反序列化Java对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19394555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:47:26  来源:igfitidea点击:

Serialize/Deserialize Java object through network and byte array

javaserialization

提问by prosseek

I have this code from DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html) that serialize/deserialize Java object from/to file.

我有这个来自 DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html)的代码,它从/到文件序列化/反序列化 Java 对象。

final class Hello implements Serializable
{
    int x = 10;
    int y = 20;

    public int getX()
    {
        return x;
    }
    public int getY()
    {
        return y;
    }
}


public class SerializedComTest {

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void testFile() throws IOException, ClassNotFoundException {
        Hello h = new Hello();
        FileOutputStream bs = new FileOutputStream("hello.txt"); // ("testfile");
        ObjectOutputStream out = new ObjectOutputStream(bs);
        out.writeObject(h);
        out.flush();
        out.close();

        Hello h2;
        FileInputStream fis = new FileInputStream("hello.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        h2 = (Hello) ois.readObject();

        assertTrue(10 == h2.getX());
        assertTrue(20 == h2.getY());
    }
}

How can I transfer serialized object using Java socket? And also how can I store the serialized/deserialized object to/from a byte array.

如何使用 Java 套接字传输序列化对象?以及如何将序列化/反序列化的对象存储到/从字节数组中存储。

采纳答案by prosseek

This is the code for serialization to/from byte array. I got hints from - Java Serializable Object to Byte Array

这是用于序列化到/从字节数组的代码。我得到了提示 - Java Serializable Object to Byte Array

@Test
public void testByteArray() throws IOException, ClassNotFoundException, InterruptedException {
    Hello h = new Hello();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeObject(h);
    byte b[] = bos.toByteArray();
    out.close();
    bos.close();

    Hello h2;
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    ObjectInput in = new ObjectInputStream(bis);
    h2 = (Hello) in.readObject();

    assertTrue(10 == h2.getX());
    assertTrue(20 == h2.getY());
}

回答by wtfmoments

Like you wrapped your filestream with the objectstream class, you do the same with sockets. You should not"store" a serialized object to a string.

就像你用 objectstream 类包装文件流一样,你对套接字做同样的事情。你应该不是“存储”一个序列化对象的字符串。

回答by user207421

How can I transfer serialized object using Java socket?

如何使用 Java 套接字传输序列化对象?

Wrap its output stream in an ObjectOutputStream.

将其输出流包装在ObjectOutputStream.

And also how can I store the serialized/deserialized object to/from a string.

以及如何将序列化/反序列化的对象存储到字符串中。

You don't. Serialized objects are binary, and should be stored in byte arrays. A deserialized object is the object itself, not a string.

你没有。序列化对象是二进制的,应该存储在字节数组中。反序列化对象是对象本身,而不是字符串。

You don't need those readObject()and writeObject()methods. They don't do anything that wouldn't happen by default.

你不需要那些readObject()writeObject()方法。他们不会做任何默认情况下不会发生的事情。

回答by prosseek

This is the code that works, and I got the hint from http://cyberasylum.janithw.com/object-serialization-over-networks-in-java/.

这是有效的代码,我从http://cyberasylum.janithw.com/object-serialization-over-networks-in-java/得到了提示。

@Test(timeout = 2000)
public void testStream() throws IOException, ClassNotFoundException, InterruptedException {
    PingerThread pinger = new PingerThread(9092);
    pinger.start();

    String serverAddress = "localhost";
    Socket s;
    PrintWriter output;
    BufferedReader input;
    try {
        // Client
        s = new Socket(serverAddress, 9092);
    }
    catch (IOException e)
    {
        // when error, try again
        Thread.sleep(500);
        s = new Socket(serverAddress, 9092);
    }

    // send the object over the network
    Hello h = new Hello();

    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
    out.writeObject(h);
    out.flush();

    ObjectInputStream in = new ObjectInputStream(s.getInputStream());
    System.out.println("2");
    Hello h2;
    h2 = (Hello) in.readObject();

    assertTrue(10 == h2.getX());
    assertTrue(20 == h2.getY());
}

private class PingerThread extends Thread {
    public int portNumber;

    public PingerThread(int portNumber) {
        super();
        this.portNumber = portNumber;
    }

    @Override
    public void run() {
        try {
            ServerSocket listener = new ServerSocket(this.portNumber);
            Socket socket = listener.accept();

            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

            Hello h;

            while((h = (Hello) in.readObject()) != null) {
                System.out.println("1");
                //h = (Hello) in.readObject();
                System.out.println(h.getX());
                System.out.println(h.getY());

                out.writeObject(h);
                out.flush();
            }

            System.out.println("OUT");
            socket.close();
            listener.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}