How to transfer objects over network using java

前端 未结 4 517
执笔经年
执笔经年 2021-01-14 14:06

what is the library should I use ? what are the functions that help me?

4条回答
  •  天涯浪人
    2021-01-14 14:23

    ObjectOutputStream/ObjectInputStream.

    The whole logic is approximately as follows. Adjust by the demands of your app.

    Send:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(objectToSend);
    oos.close();
    
    byte[] bytes = baos.toByteArray();
    socket.write(bytes);
    

    Receive:

    ObjectInputStream ois = new ObjectInputStream(socketInputStream);
    MyObject mo = (MyObject)ois.readObject();
    

提交回复
热议问题