5

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.

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.

prosseek
  • 182,215
  • 215
  • 566
  • 871

4 Answers4

13

This is the code for serialization to/from byte array. I got hints from - 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());
}
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871
1

How can I transfer serialized object using Java socket?

Wrap its output stream in an 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.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

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.

wtfmoments
  • 16
  • 1
0

This is the code that works, and I got the hint from 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();
        }
    }
}
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • No caveat. Your citation is mistaken on that point. He says himself he is guessing. The Object streams should be created once each per socket and used for the life of the socket. He is also mistaken about how to resolve the deadlock. All that is required is that the `ObjectOutputStream` should be created first, before the `ObjectInputStream,` at at least one end, preferably both. There's nothing in this answer that isn't implied by the other answers and your own code in your question. – user207421 Oct 16 '13 at 03:46