简体   繁体   English

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

[英]Serialize/Deserialize Java object through network and byte array

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? 如何使用Java套接字传输序列化对象? And also how can I store the serialized/deserialized object to/from a byte array. 还有如何将序列化/反序列化对象存储到字节数组中/从字节数组存储。

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());
}

Like you wrapped your filestream with the objectstream class, you do the same with sockets. 就像你用objectstream类包装文件流一样,你也可以使用套接字。 You should not "store" a serialized object to a string. 应该“存储”的序列化对象的字符串。

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. 您不需要那些readObject()writeObject()方法。 They don't do anything that wouldn't happen by default. 他们不做任何默认情况下不会发生的事情。

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();
        }
    }
}

暂无
暂无

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

相关问题 如何将内部没有 Serializable 字段的 java 对象序列化为字节数组并反序列化该数组以获取原始对象 - How to serialize a java object with not Serializable fields inside it into byte array and deserialize the array to get the original object 如何将Httpclient的响应object序列化和反序列化为字节数组 - How to serialize & deserialize response object of Httpclient into byte array 如何使用 Jackson 和包装器 object 反序列化/序列化字节数组 - how to deserialize / serialize byte array using Jackson and wrapper object 将Integer集合序列化为字节数组,然后反序列化 - Serialize Integer collection to byte array and deserialize it back Java:如何将对象序列化为字节数组,且输出字节越少越好? - Java: how to serialize object into byte array with as few output bytes as possible? 如何在Java中使用紧凑字节将对象序列化为字节数组 - How to Serialize object to byte array with compact bytes in java 当我有一个黑盒子转换为/从字节数组转换时,如何在Java中序列化和反序列化? - How do I serialize and deserialize in Java when I have a black box to convert to/from a byte array? 如何快速序列化/反序列化复杂的Java对象 - How to serialize/deserialize complex java object quickly 序列化和反序列化 Java object 具有 vavr 列表 - Serialize and Deserialize Java object having vavr list Jackson:用一个数组字段序列化/反序列化 object - Jackson: serialize / deserialize object with one array field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM