[英]Sending serialized objects and byte[] from same stream
I have a client server application, they communicate throught objectoutputstream and objectinputstream. 我有一个客户端服务器应用程序,它们通过objectoutputstream和objectinputstream进行通信。 I send serialized objects from one to other, but now i want to send files also.
我将序列化的对象从一个对象发送到另一个对象,但是现在我也想发送文件。 If i pass the byte[] of file inside a serialized object it can be transmitted but the object stays at objectoutputstream and objectinputstream and after some sends if the file is big enough i get memory exception.
如果我在序列化对象内部传递文件的byte [],则可以传输该对象,但是对象停留在objectoutputstream和objectinputstream上,如果文件足够大,则在发送一些消息后,我会得到内存异常。 If i send it like:
如果我像这样发送:
File file = new File("C:\\a.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024*1024*10];
int n = -1;
while((n = bis.read(buffer))!=-1) {
oos.write(buffer,0,n);
}
and read it: 并阅读:
while ((fromServer = ois.read()) != null) {
}
works well. 效果很好。
My question is, do i have to implement a system to know if i have to writeObject/readObject or just write/read? 我的问题是,我是否必须实施一个系统来知道是否必须要writeObject / readObject还是只需要写/读? Do i have to get rid of serialized communication, do i have to create another streams for read and write?
我是否必须摆脱串行通信,是否必须创建另一个用于读取和写入的流?
You have to define a protocol which doesn't have any ambiguity, and stick to this protocol on the client and server. 您必须定义一个没有歧义的协议,并在客户端和服务器上坚持使用该协议。
For example, if you send a stream of bytes, and then an object, you have no way, at the receiving side, to know when the stream of bytes ends, and when the object begins. 例如,如果先发送一个字节流,然后再发送一个对象,则在接收端,您将无法知道字节流何时结束以及对象何时开始。
A protocol to sole this problem might be: 解决此问题的协议可能是:
The receiving side can then read the size (N), then read N bytes from the stream, then read the object. 然后,接收方可以读取大小(N),然后从流中读取N个字节,然后读取对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.