java超过一定人数怎么办,Java的StreamCorruptedException超过一定尺寸发送包含字节数据对象时...

I have a Java client-server (using ocsf if anyone here knows it) infrastructure I am using to upload files from client to server. The client is actually an Android app (not sure if that matters that much or not in this case)

I am doing this by reading the file data (bytes), wrapping it in an object that contains some other details (user id, etc..) and sending this object over ObjectOutputStream to the server.

It seems everything works fine until the byte array of the file is over a certain size (not sure what this strange threshold is yet but it seems 645KB is already too much). Then, the server throws a StreamCorruptedException when trying to read the object from the ObjectInputStream and closes the socket.

The code of the object message containing the file bytes:

public class MessageUploadFile extends MessageToServer {

private static final long serialVersionUID = 2356276507283427913L;

private String _destId;

private TransferDetails _td;

private byte[] _fileData;

public MessageUploadFile(String srcId, TransferDetails td, byte[] fileData){

super(srcId);

_destId = td.getDestinationId();

_td = td;

_fileData = fileData;

}

The client side socket and streams initialization:

clientSocket= new Socket(host, port);

output = new ObjectOutputStream(clientSocket.getOutputStream());

input = new ObjectInputStream(clientSocket.getInputStream());

Sending the message using:

output.writeObject(msg);

These are the streams initialization on the server side:

input = new ObjectInputStream(clientSocket.getInputStream());

output = new ObjectOutputStream(clientSocket.getOutputStream());

Reading the message using:

msg = input.readObject();

解决方案

StreamCorruptedException

A Java StreamCorruptedException can be thrown while deserialising data. It essentially occurs in one of two main cases:

you try to open an ObjectInputStream around some data that wasn't actually written using an ObjectOutputStream

OR

During a readObject() operation, the stream gets in the "wrong place".

From java docs:

Thrown when control information that was read from an object stream violates internal consistency checks.

But I got this exception with large message and moved to byte array solution.

In summary, convert Object to and from byte array and re-create it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值