3

java | 网络序列化

 1 year ago
source link: https://benpaodewoniu.github.io/2023/01/28/java219/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java | 网络序列化

使用 ByteArrayOutputStreamByteArrayInputStream 进行网络传递。

关于序列化请参考 java | Serializable接口

这两个流实际就内存流:顾名思义就是将数据写入内存,从内存中读取数据;

  • ByteArrayOutputStream
    • 字节数组输出流在内存中创建一个字节数组缓冲区,所有发送到输出流的数。据保存在该字节数组缓冲区中。实际作用就是通过 write() 将对象各个字段写入一个字节数组,然后在使用 toByteArray() 将字节数据取出来,通过 tcp 传输给服务器。
  • ByteArrayInputStream
    • 字节数组输入流在内存中创建一个字节数组缓冲区,从输入流读取的数据保存在该字节数组缓冲区中。实际就是将客户端发送过来的消息转成byte数组,存入内存,在分批次读取数据。

Message 进行序列化和反序列化。

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(message);
byte[] bytes = bos.toByteArray();
byte[] bytes = ...;
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
Message message = (Message)objectInputStream.readObject();

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK